Saturday, August 24, 2013

Check if Checkbox is checked using jQuery

Yesterday I need to find out if checkbox is checked or not using jQuery. I was knowing one way to find out but there are couple of other ways as well to find out if checkbox is checked using jQuery. In this post, you will find all different possible ways.

Related Post:

  • Check if radio button is checked or selected using jQuery
  • Common jQuery Mistakes

1. First Way:

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.
1var 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".
So if you want to have true or false, then you need to use conditional expression as I have done in the code.

2. Second Way
1var isChecked = $('#chkSelect:checked').val()?true:false;
$('#chkSelect:checked').val() method returns "on" when checkbox is checked and "undefined", when checkbox is unchecked.

3. Third Way
1var isChecked = $('#chkSelect').is(':checked');
The above method uses "is" selector and it returns true and false based on checkbox status.
4. Fourth Way

The below code is to find out all the checkbox checked through out the page.

1$("input[type='checkbox']:checked").each(
2    function() {
3       // Your code goes here...
4    }
5);