在页面加载时重新加载下拉菜单

时间:2012-12-18 19:11:27

标签: php mysql select

我有一个html表单,我一直用它来POST到php表单,这会将发布的数据保存到数据库中。我现在正在单击编辑时将数据加载到表单中,这对于文本字段工作正常,因为我可以使用

value="<?php echo $somefield ?>" 

问题是我不知道如何重新选择我的下拉菜单。菜单看起来像这样,用于选择类别,但当页面重新加载时没有任何反应,下拉列表不会重新加载。

    <select name="category" id="category">
    <option>- Select A Category -</option>
      <optgroup label="Tractors">
      <option value="Tractor">Tractor</option>
      <option value="Compact">Compact</option>
    <option value="Forklift">Forklift</option>
    <option value="Load All">Load All</option>
    <option value="Loader">Loader</option>
    <option value="Maniscopic">Maniscopic</option>
    <option value="Masted">Masted</option>
    <option value="Piviot">Piviot</option>
    <option value="Telescopic">Telescopic</option>
    <option value="UTV">UTV</option>
      </optgroup>
      <optgroup label="Machinery">
      <option value="Attachments">Attachments</option>
      <option value="Bale Handling">Bale Handling</option>
      <option value="Cultivation Equipment">Cultivation Equipment</option>
      <option value="Drills">Drills</option>
      <option value="Feeders">Feeders</option>
      <option value="Fertlizer Spreaders">Fertlizer Spreaders</option>
      <option value="Grass Harrows">Grass Harrows</option>
      <option value="Grassland Equipment">Grassland Equipment</option>
      <option value="Hedge Cutters">Hedge Cutters</option>
      <option value="Mowers">Mowers</option>
      <option value="Muck Spreaders ">Muck Spreaders </option>
      <option value="Ploughs">Ploughs</option>
      <option value="Post Hammers">Post Hammers</option>
      <option value="Power Harrows">Power Harrows</option>
      <option value="Rakes">Rakes</option>
      <option value="Rolls">Rolls</option>
      <option value="Rotovators">Rotovators</option>
      <option value="Shredders">Shredders</option>
      <option value="Splitters">Splitters</option>
      <option value="Sprayers">Sprayers</option>
      <option value="Spreaders">Spreaders</option>
      <option value="Tankers">Tankers</option>
      <option value="Tedders">Tedders</option>
      <option value="Toppers">Toppers</option>
      <option value="Trailers">Trailers</option>
      <option value="Wrappers">Wrappers</option>

      </optgroup>
      <optgroup label="Forklifts">
      </optgroup>
    </select>

2 个答案:

答案 0 :(得分:2)

构建列表时,所选选项应具有selected =“selected”属性。

答案 1 :(得分:2)

<?php

  echo '<select>';
  foreach( $names as $name )
    echo '<option value="'.$name.'" '.($name==$selected?' selected="selected"':'').'>'.$name.'</option>'

  echo '</select>';

?>