Reputation: 5561
Hi Guys i want to check and uncheck the check box of my form using PHP script. in database i am using datatype TinyInt for storing either 0 or 1. I am using following code.
<tr>
<td><div id="formEditProfileLblAEmail">Allow Email</div>
</td><td><input type="checkbox" checked="<?php
$sql = "Select firstname,middlename,lastname,nickname,require_email,allow_scores from user_info where username = '".$_SESSION['username']."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row = mysql_fetch_array($result);
if($count>0)
{
if($row['require_email']=='1')
{
echo 'checked';
}
else
{
echo 'unchecked';
}
}
else
echo 'unchecked';
?>" name="formEditProfileChkAEmail" id="formEditProfileChkAEmail" /> </td></tr>
But My Check box is always coming checked whether i am having 0 or 1 in database.
Upvotes: 1
Views: 11377
Reputation: 103817
According to the HTML specs, the checked
attribute is boolean. That is, if you don't set it to a value that implies false, the user agent will probably decide that it is true, i.e. checked. Historically the mere presence of this attribute indicated that the box should be checked, hence why this is the likely default value.
You can test this by looking at the source - I suspect you'll have your page rendered with checked="unchecked"
, which will still render the box as checked.
You can fix this by changing "unchecked" to "false" in your PHP source, in order to get the correct boolean behaviour you're looking for.
Edit: the specs further go on to define that boolean attributes can only take one legal value (which implies true
) - so to produce correct HTML with this attribute set to false
, the only way to do this is to omit the attribute altogether. Shakti Singh's answer describes how to achieve this (and gets a +1 from me).
Upvotes: 2
Reputation: 2654
There is no value such as "unchecked" for the checked property, so you need to echo:
checked="checked"
if the value is > 0 and nothing at all if it's 0.
Upvotes: 1
Reputation: 86406
Do not do with else part of if just add inside if
Remove the checked="
which is outside the if
<input type="checkbox"
<?php if($row['require_email']=='1') {
echo 'checked="checked"';
}
Nothing to do with checkboxes which you want them to be unchecked.
Upvotes: 5