Newton_Jose
Newton_Jose

Reputation: 141

In a HTML form how can I do to access via PHP a option from select tag by optgroup?

In a HTML form how can I do to access via PHP a option from select tag by optgroup? It's possible?

It would be like this:

<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 } ?>

Upvotes: 0

Views: 37

Answers (1)

Barmar
Barmar

Reputation: 780851

Include the optgroup name in the option values.

<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>

Then when you're processing the form data, you can check the beginning of the value.

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

Upvotes: 1

Related Questions