Search code examples
phphtmlformslabeloptgroup

optgroup get in php label associated


I have following code in a html form

<select name="category" class="input" onchange="ShowTB(this,'suggest');">
      <option value="0" selected="selected">
        [choose yours]
      </option>
      <optgroup label="Item">
      <option value="SubItem1"SubItem1</option>
    <option value="SubItem2">SubItem2</option>
  </optgroup>
      <option value="Item2">Item2</option>
      <optgroup label="Item3">
     <option value="SubItem4"SubItem4</option>
     <option value="SubItem5">SubItem5</option>
  </optgroup>
      <option value="Item4">Item4</option>
<option value="Item5">Item5</option>
<option value="Item6">Item6</option>
<option value="Item7">Item7</option>

</select>

in php i get the value of field selected with:

$category = $_POST['category'];

in this mode if i select in the form ie: SubItem1 , in php i get value SubItem1 but i want also get associated label ie: Item or if i select SubItem5 i get SubItem5 but i want also get associated label ie: Item3 How to ?


Solution

  • Indeed, you only get the value. If you need more, just encode whatever you want into the value, for example:

    <option value="Item3.SubItem5">SubItem5</option>
    

    Alternatively, you could use javascript to catch onChange events on the select field and update a hidden input field with the desired label.