ungalnanban
ungalnanban

Reputation: 10327

how to set value for <select> tag

Using Php I have wrote the drop down list box code. for Edit employee details I have used the same code and I tried to set the value on list box but the value is not set. how to do this.

Employee Name: <select name=emp_name *$value='$name'*>
<option> -- EMPLOYEE NAME -- </option>
<?  
    while ($q->fetchInto($row)){
        print "<option>$row[0]</option>";
    }
?>
</select>

Upvotes: 1

Views: 7415

Answers (4)

Jon Weers
Jon Weers

Reputation: 1631

You have to set the selected option to selected while building the options like so:

<select name='emp_name'>
  <?
    //Define the array of possible options.
    //This can come from the database fetch such as:
    $options = $q->fetchMutipleVals();
    //Or defined manually such as:
    $options = array('value1'=>'label1', 'value2'=>'label2'); //etc.
    foreach ($options as $val => $label){
      $selected = ($name == $val)? "selected='selected'":''; //sets html flag
      echo "<option value='$val' $selected>$label</option>\n";
    }
  ?>
 </select>

Upvotes: 4

Mark Elliot
Mark Elliot

Reputation: 77024

Test for the right value as you iterate and mark the <option> you want to have as the selected value by using the selected='selected' attribute:

Employee Name: <select name="emp_name">
<option> -- EMPLOYEE NAME -- </option>
<?php
    while ($q->fetchInto($row)){
        if($row[0] == $name){
           $selected_text = " selected='selected'";
        }else{
           $selected_text = "";
        }
        print "<option{$selected_text}>{$row[0]}</option>";
    }
?>
</select>

Upvotes: 2

bimbom22
bimbom22

Reputation: 4510

try

Employee Name: < select name=emp_name $value='$name' > <    option > -- EMPLOYEE NAME -- < / option >

< ? while ($q->fetchInto($row))

{ print "<option>$row[0]</option>"; } < / select >

? >

Upvotes: 0

fmark
fmark

Reputation: 58547

You need the option tag you wanted selected to have a selected attribute:

<select>
  <option> -- EMPLOYEE NAME -- </option>
  <option>Sally</option>
  <option selected="selected">Fred</option>
  <option>Liz</option>
</select>

Upvotes: 1

Related Questions