seno71625 seno71625 - 1 month ago 8
PHP Question

Why is Checked attribute not working for radio button using PHP?

Here is my code snippet:

echo "<tr>
<td>Fruits</td>
<td>
<input type='radio' name='fruit' value='Apple' ($fruit=='Apple')?'checked':''> Apple
<input type='radio' name='chamber' value='Banana' ($fruit=='Banana')?'checked':''> Banana</td>
</tr>";


Value of
$fruit
is
Apple
but still the the radio button attribute is not being set to
checked
.

Answer

If you check the output of this you can see that the statement will not execute as you want because it's inside the " ". You need to break the " before and continue after the check like this:

echo "<tr>
 <td>Fruits</td>
 <td>
 <input type='radio' name='fruit' value='Apple'  " .  (($fruit=='Apple')?'checked="checked"':'') . "> Apple
 <input type='radio' name='chamber' value='Banana' " .(($fruit=='Banana')?'checked="checked"':'') . "> Banana</td>
</tr>";

And better to include all inside brackets (...) to not mess with something else.

Also it's better to have checked="checked" when you want to mark something as checked.

Comments