简体   繁体   中英

I want to check and uncheck the check box of my form using PHP script

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.

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.

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, ie 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).

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.

Is the text being printed at all? Try checked="checked" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM