简体   繁体   中英

Check a check box is checked or not using jquery

I want to check a checkbox is checked or not using jquery. When click on the check box, check the checkbox is checked or not using jquery. My code is given below.

   <script>
   function check(id)
    {
     if($("#id:checked").length == 1)
      {
        alert("cheked");
      }
    }
   </script>


     Html
     $i=1;
     <input name="" type="checkbox" value="" 
     id="one<?php echo $i; ?>"  onclick="check(one<?php echo $i; ?>)"/>

Pass the element reference to the method

<input name="" type="checkbox" value="" id="one<?php echo $i; ?>"  onclick="check(this)"/>

then check the checked property value

function check(el) {
    if (el.checked) {
        alert("cheked");
    }
}

Note: Since you are using jQuery, instead of using inline event handlers try to use jQuery event handlers


In your script the problem is, id is a variable holding the actual id so you need to use string concatenation

function check(id) {
    if ($("#" + id + ":checked").length == 1) {
        alert("cheked");
    }
}

Also since the id is a string, it has to be enclosed in a '' in the click handler call

<input name="" type="checkbox" value="" id="one<?php echo $i; ?>"  onclick="check('one<?php echo $i; ?>')"/>

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