Wednesday 24 April 2013

Different ways to checking the checkbox using jQuery


There are couple of other ways as well to find out if checkbox is checked using jQuery,…

Method 1 :

Below single line of code will provide the status of checkbox using jQuery. It checks whether the checked is checked or not using jQuery and will return 1 or 0.

      var isChecked = $('#chkSelect').attr('checked')?true:false;

I have noticed that on many website it is written that 'checked' attribute will return true or false, but this is not correct. If the checked box is checked then it return status as "checked", otherwise "undefined". 
 
Method 2 :
 
      var isChecked = $('#chkSelect:checked').val()?true:false;
 
$('#chkSelect:checked').val() method returns "on" when checkbox is checked and "undefined", when checkbox is unchecked.

Method 3 :

      var isChecked = $('#chkSelect').is(':checked');
 
The above method uses "is" selector and it returns true and false based on checkbox status.
 
Method 4 :
 
The below code is to find out all the checkbox checked throughout the page.
 
$("input[type='checkbox']:checked").each( 
    function() { 
       // Your code goes here...
    } 
);


-Thanks

No comments:

Post a Comment