Search code examples
phphtmlformsdrop-down-menuselectedindex

Specify a default selected item for HTML form drop-downs


Typically when you need to select an item by default, you do:

<select>
  <option value="1">                 Volvo  </option>
  <option value="2" selected="true"> Saab  </option>
  <option value="3">                 Mercedes  </option>
  <option value="4">                 Audi  </option>
</select>

Is it possible to get something like this?

<select selectedValue="2">
  <option value="1">  Volvo  </option>
  <option value="2">  Saab  </option>
  <option value="3">  Mercedes  </option>
  <option value="4">  Audi  </option>
</select>

It works out easier in PHP since you only have to soft-code one value, instead of handling the selected attribute on any possible <option/>.


Solution

  • Put JavaScript after the declaration of the listbox and set the selected index there:

    <script>
    document.getElementById('listBoxId').selectedIndex=<?php echo $INDEX ?>;
    </script>
    

    Something like this.