Any way to define selected inside <select> tag rather than on <option>

[亡魂溺海] 提交于 2019-12-02 01:50:44

No.

Multiple options can have the same value and (if the multiple attribute is set) multiple options can be selected at the same time, so having an attribute to specify the value wouldn't be feasible.

You can't change the <select> element to specify this: it's not part of the HTML specification. What you can do is give each option element an id and then use Javascript to set the right option element(s) as selected. In PHP, you would need to output the script snippet in the right place to get the browser to run it.

For example

<option value="7ft - 213cm" label="7ft - 213cm" id="s23">7ft - 213cm</option>
...
<script>
document.getElementById("s23").selected=true
</script>

You could always just write a helper function that gives you the <option> by passing it parameters. Something along the lines of

function get_option($value, $selected_value) {
    return '<option value="' . $value . '" label="' . $value . '"' . ($value == $selected_value ? ' selected="selected"' : '') . '>' . $value . "</option>\n";
}

This will keep you from having to write it for each value, but instead just do

$selected_value = '4ft 5in - 134cm';
echo get_option('4ft 5in - 134cm', $selected_value);
echo get_option('4ft 6in - 137cm', $selected_value);
//etc, etc

You can put all items in an array and dynamically generate the list with a for (or foreach) loop. Then just check in this loop whether your loopvariable equals your value and if so, assign the selected attribute.

Something like this:

<select name="height" id="height">
    <option value="" label="Select">Select Height</option>
    <?php
    $options = array("4ft 5in - 134cm", "4ft 6in - 137cm", "4ft 7in - 139cm", /* and all your other options ... */);
    $yourvalue = "4ft 6in - 137cm"; // or any valid entry
    foreach($options as $option) {
        echo '<option value="'.$option.'" label="'.$option.'" '. ($option == $yourvalue ? 'selected' : '') .'>'.$option.'</option>';
    }
    ?>
</select>

If you don't want to use javascript, you're going to have to write the code you're avoiding.

<? $selected = "6ft 10in - 208cm"; ?>
<select name="height" id="height">
  <option value="" label="Select">Select Height</option>
  <? foreach ( $options as $option ): ?>
    <option value="<?= $option; ?>" <?= ($option == $selected ? "selected" : ""); ?> ><?= $option; ?></option>
  <? endforeach; ?>
</select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!