【问题标题】:In a HTML form how can I do to access via PHP a option from select tag by optgroup?在 HTML 表单中,如何通过 PHP 从 optgroup 的选择标记中访问选项?
【发布时间】:2020-09-22 18:53:54
【问题描述】:

在 HTML 表单中,如何通过 PHP 从 optgroup 的选择标记中访问选项? 有可能吗?

应该是这样的:

<select name="est" id="est">
  <optgroup name="G1" label="Group 1">
    <option>Opção 1.1</option>
  </optgroup> 
  <optgroup name="G2" label="Group 2">
    <option>Opção 2.1</option>
    <option>Opção 2.2</option>
  </optgroup>
</select>
<?php if($name == "G2") { do something } ?>

【问题讨论】:

  • optgroups 对服务器不可见,它们仅用于对客户端上的选项进行分组。

标签: php html forms select optgroup


【解决方案1】:

在选项值中包含 optgroup 名称。

<select name="est" id="est">
  <optgroup name="G1" label="Group 1">
    <option value="G1-1">Opção 1.1</option>
  </optgroup> 
  <optgroup name="G2" label="Group 2">
    <option value="G2-1">Opção 2.1</option>
    <option value="G2-2">Opção 2.2</option>
  </optgroup>
</select>

那么当你在处理表单数据的时候,你可以检查值的开头。

list($name, $value) = explode("-", $_POST["est"]));
if ($name == "G2") {
    // do something
}

【讨论】:

  • 脚本中的PHP代码是处理表单提交的吗?
  • 没有。它在 HTML 中
  • 这毫无意义。在您提交表单之前,输入不可用。在提交表单之前,您想对 optgroup 做什么?
  • 如果需要在提交前进行处理,需要使用客户端JavaScript,而不是PHP。
  • 我解决了!它只是 substr($value,0,2)。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 2022-07-16
相关资源
最近更新 更多