Specify a default selected item for HTML form drop-downs

*爱你&永不变心* 提交于 2019-12-04 14:29:40
dmitko

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.

There is no attribute like that on the <select> element. Assuming your <option> output is in a loop, I don't see how it makes a huge difference:

$selected = "2";
foreach($values as $key => $val) {
    echo "<option value=\"" . $key . "\"" . ($key == $selected ? " selected=\"selected\">" : ">") . $val . "</option>";
}

(my PHP is a little rusty, that may not be 100% correct)

No, but you can add your default value to your id like

<select id="default-value-2">

then in your options, you have

<option value="2" <?php echo is_this_the_default_value ? selected='true' : '' ?>

or something to that effect(forgive me i forgot my php syntax, but i hope you get the point).

Anyway, that is a dirty fix also, so i suggest just adding a method to check for the default selected tag and printing it selected="selected" when it is the default. You can just call it once if you loop through your select options

Serendipity

You can do it like this:

$value = 1;

<select>
<?php if($value==1) echo "<option selected='true'> Volvo </option>";
else echo "<option> Volvo </option>"; ?>
<?php if($value==2) echo "<option selected='true'> Saab </option>";
else echo "<option> Saab </option>"; ?>
</select>

I found myself googling this to see if there was a better way to do it.

The best and cleanest answer is from @roryf, however if you are not looping through your data I thought it would be a lot cleaner to wrap it up in a function:

function set_selected($desired_value, $new_value)
{
    if($desired_value==$new_value)
    {
        echo ' selected="selected"';
    }
}

Then you would use it like this:

<?php $selected_value = 2; ?>

<select>
    <option value="1"<?php set_selected('1', $selected_value); ?>> Volvo  </option>
    <option value="2"<?php set_selected('2', $selected_value); ?>> Saab  </option>
    <option value="3"<?php set_selected('3', $selected_value); ?>> Mercedes  </option>
    <option value="4"<?php set_selected('4', $selected_value); ?>> Audi  </option>
</select>

This would set Saab as selected :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!