I have a weird html option list which I dont want to check each value to make it selected or not see the list below
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>
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>
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>