I have a select box where the user chooses a sex (gender) from a drop down, and their choice is specified with "selected" in the select tag. But the box always ends up 'Choose'. What is wrong in the following syntax?
echo"<select name='sex'>
<option value='N' '". ($info['sex'] == "N" ? 'selected=selected':'') ."'>Choose</option>
<option value='M' '". ($info['sex'] == "M" ? 'selected=selected':'') ."'>Male</option>
<option value='F' '". ($info['sex'] == "F" ? 'selected=selected':'') ."'>Female</option>
</select>";
The $info['sex']
is from a consult SQL that return always N, M or F.
Your selected=selected
is being quoted and output like
<option value='N' 'selected=selected'>
when you run your code, use this
echo"<select name='sex'>
<option value='N' ". ($info['sex'] == "N" ? 'selected=\'selected\'':'') .">Choose</option>
<option value='M' ". ($info['sex'] == "M" ? 'selected=\'selected\'':'') .">Male</option>
<option value='F' ". ($info['sex'] == "F" ? 'selected=\'selected\'':'') .">Female</option>
</select>";
notice the escaped quotes at 'selected=\'selected\''
and the lack of single-quotes at ". ($info['sex']
and .">
demo: http://codepad.org/AX95BzTR
here's a fiddle showing your problematic output: http://jsfiddle.net/JKirchartz/KB4rv
It should be:
selected=\"selected\"
Don't really know if this is the answer, but try this: ". (($info['sex'] == "N") ? ('selected=\'selected\''):(NULL)) ."
Also look if you tag has autocomplete="off" or hit ctrl + f5 a few times to be sure. This happend to me alot in the past
First of all, try to avoid this style of coding and include PHP in HTML not the other way.
For example it can be done like this:
<?php
$sex = "F"; //mockup data from DB
?>
<select>
<option <?= $sex=="M" ? "selected='selected'" : "" ?> value='M' >Male</option>
<option <?= $sex=="F" ? "selected='selected'" : "" ?> value='F' >Female</option>
</select>
if $info['sex']
is N or M or F;
echo "<select name=\"sex\">
<option value=\"N\" ". ($info['sex'] == "N" ? "selected=\"selected\"" : "") .">Choose</option>
<option value=\"M\" ". ($info['sex'] == "M" ? "selected=\"selected\"" : "") .">Male</option>
<option value=\"F\" ". ($info['sex'] == "F" ? "selected=\"selected\"" : "") .">Female</option>
</select>";
PS: Single quotes is valid to use in HTML but it's a bad trend like justin biebering.