EricBellDesigns
EricBellDesigns

Reputation: 965

Checkbox checked attribute not toggling

I came across a strange issue when attempting to add jQuery functionality initiated by a checkbox. My checkbox appears to be toggling the checked attribute, since visually the check mark toggles on click, but the "checked" attribute actually never changes.

Here's an example of my issue: http://jsfiddle.net/ez710gxL/3/

<input id="check_box_2" class="css-checkbox padding-left-3" type="checkbox" checked="checked" />
<label for="check_box_2" name="cb_lbl_2" class="css-label" style="margin-top:5px; margin-left:10px;">Show Note</label>

My question is: If the checked attribute does not change, how can I use jQuery to determine if the checkbox is checked or not?

Upvotes: 1

Views: 4901

Answers (2)

EricBellDesigns
EricBellDesigns

Reputation: 965

Ok, so apparently the issue was not with the prop/attr toggling "checked", but rather the property updating when viewing the browser's developer tools. When I inspect the checkbox, the checked property ALWAYS stays "checked", however the following code works to determine if the checkbox is actually checked or not (@War10ck's suggested code):

$('#check_box_2').is(':checked')

Upvotes: 3

Dave
Dave

Reputation: 10924

Use jQuery .prop() instead of .attr()

Set the .prop("checked", true). This is one of the greatest benefits of .prop() over .attr() since .prop() can set values that are non-strings.

Here's a working example on how to use it:

setInterval(function() {
  if ($("#chkBox1").prop("checked"))
    $("#chkBox1").prop("checked", false);
  else
    $("#chkBox1").prop("checked", true);
  }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="Test" id="chkBox1" checked />

Upvotes: 3

Related Questions