Introduction to JQUERY - Checking Check and Radio boxes using the :checked Selector

Guest Posts Paolo Nikko Nuñal

In our previous tutorial we talked about on how to deal with drop-downs and determine if they are selected or not using the :selected selector. In this tutorial we are going to deal with checkboxes, radio-buttons and select elements using the :checked selector.

Syntax:

$(":checked");

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
   $("#btn-check").click(function(){
          if($('input[id="checkbox_id"]:checked').length == 1){
                 alert("Sony is Checked");
          }
          else{
                alert("Sony is not Checked");
           {
      });
});
</script>
</head>
<body>
<input type="checkbox" id="checkbox_id" name="checkbox_name" class="checkbox_class" value="Sony" /> Sony
<button type="button" id="btn-check">Check</button>
</body>
</html>


From the code above, everytime you select the "Check" button it will automatically verify if the Sony checkbox is selected or not. However, we did add a few parameters aside from the :checked selector. As you can see we are checking the checkbox though its ID which has a name of "checkboxid". Additionally, we can also check it through the use of class and name.

Using name:

('input[name="checkbox
name"]:checked')

Using class:

('input[class="checkboxclass"]:checked')

The reason why we use the numerical value 1, its because checked items return 1 and 0 for unchecked items.

If you are looping through an array of checkboxes sharing the same name or class then you can loop through them. Using the example code below.

Code

var cellphones = $('input[name="checkbox
name"]:checked');

$(cellphones).each(function(){
//DO SOMETHING HERE
});

There you have it!, that's how you check a checkbox. You can also do the same with radio boxes and see which one is being selected.