从下拉框中保存所选选项

时间:2013-03-05 12:48:00

标签: php javascript drop-down-menu

<form method="post">
  <select name="select_employee" id="select_employee">
    <?php $allemp=$this->AllEmployees; ?>
    <option selected value="">Select an employee..</option>
    <?php foreach($allemp as $row){ echo "<option value=".$row[ 'Id']. ">".$row[ 'Etunimi']. " - ". $row[ 'Sukunimi']. "</option>"; } ?>
  </select>
  <input type="hidden" name="send" value="namesent">
  <input type="submit" value="submit" id="button">
</form>
<br/>
<br/>

当我提交此表单时,我会停留在同一页面上,但我希望同时保持之前选择的选项可见..我怎么能这样做? 我试过了:

document.getElementById('select_employee').value = "<?php echo $_GET['select_employee'];?>";

但它不起作用..

2 个答案:

答案 0 :(得分:1)

这里:

 foreach($allemp as $row){
     echo "<option " . (isset($_POST['select_employee']) && $_POST['select_employee'] == $row['Id'] ? ' selected ' : '') . " value=".$row['Id'].">".$row['Etunimi']." - ".$row['Sukunimi']."</option>";
}

答案 1 :(得分:0)

试试这个:

 $selected = ($row['Id'] == $_REQUEST['select_employee'])?'selected="selected"':'';
 echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
  1. echo options ($selected = ($row['Id'] == $_REQUEST['select_employee'])?'selected="selected"':'';)

  2. 上方添加了一行
  3. 在旁边选项中添加了'.$selected.'

  4. 您的代码变为:复制粘贴代码而不是您的代码

    <form method="post">
      <select name="select_employee" id="select_employee">
        <?php $allemp=$this->AllEmployees; ?>
        <option selected value="">Select an employee..</option>
        <?php foreach($allemp as $row){ 
          $selected = ($row['Id'] == $_REQUEST['select_employee'])?'selected="selected"':'';
         echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
     } ?>
      </select>
      <input type="hidden" name="send" value="namesent">
      <input type="submit" value="submit" id="button">
    </form>
    <br/>
    <br/>