I wasnt quite sure how to word the question correctly - but this is merely just out of interest really. Constantly I am having to load information from a database and pre-populate a form with the values. So in the case of the textbox, its easy, i simply set the value:
<input type="text" value="<?=$foo;?>" name="foobar">
However when I come to select boxes I find my code gets quite sloppy, as I need to place a selected
value in the line somewhere. So really I have two options, both of which I dislike:
$one = $two = "";
switch ($myval) {
case "1": $one = " selected";
case "2": $two = " selected";
}
and then in the HTML:
<select name="myval">
<option value="1"<?=$one;?>>One</option>
<option value="1"<?=$two;?>>Two</option>
</select>
Or the other option is to place a shorthand if statement in the middle of the select:
<select name="myval">
<option value="1"<?=($myval=="1") ? " selected" : "";?>>One</option>
<option value="1"<?=($myval=="2") ? " selected" : "";?>>Two</option>
</select>
Which looks slightly cleaner, however it still bugs me.
Anyone got any much more efficent ways of doing this? its even more annyoing when It is just a Yes/No
drop downbox and I have to write stupid if statements for each value.
The same question applies to checkboxes as well.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…