user6410893 user6410893 - 1 year ago 63
Javascript Question

jQuery CheckBox Selector .attr('checked) is not working?

I have a checkbox called chkBox1 and i want assign a variable true or false as per the value of selected checkbox.

<input type="checkbox" id="chkBox1">

var chkBox1Val = $('#chkBox1').attr('checked') ? true: false;

The above code is not working. How do i get the value of checkbox checked state and assigned to a variable as true/false?

var chkBox1Val = $('#chkBox1').attr('checked') === 'checked';

Or, if you are using jQuery version greater than 1.6:

var chkBox1Val = $('#chkBox1').prop('checked');

For more info, have a look at the section Attributes vs. Properties of the jQuery .prop() docs.