1
votes

I have a checkbox that when unchecked I want to confirm that the user intended to do so.

I am listening to the on.change event and use confirm() for the dialog. If the user clicks "Cancel" I have code to reset the checkbox. However, it is not obeying it. The 'checked="checked"' attribute is placed there as expected, but it does not appear as checked.

Here's a JSFiddle illustrating it: https://jsfiddle.net/0tvzLbgk/9/

Below is the code.

$('#box').on('change', 'input', function() {
  var $me = $(this);

  if (this.checked) {
    // Item has been checked, do nothing
  }
  else {
    // Item has been unchecked

    // Make sure it was not an accident
    var confirmReset = confirm("Reset checkbox?");

    if (confirmReset == true) {
      // Okay, reset
    }
    else {
      // Mistake, mark as checked again
      $me.attr('checked', 'checked');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
  <input type="checkbox" />
</div>

Does anyone know why it's not following the checked attribute?

2
Use $me.prop('checked', 'checked'); instead of $me.attr('checked', 'checked'); - Corporalis
It's worth reviewing this for an explanation as to why - Corporalis
Thanks for the link, I had seen that earlier but .attr() was working everywhere else in the code so I left it. I've updated all instances of attr() for checked to prop() now though. Thanks! - David Yeiser
No worries, there is a difference between properties and attributes and it is useful to know the difference as some times you will want to know the current state of something and other times you will want to access the value set in an attribute. It is worth reading through the jquery documentation - Corporalis

2 Answers

1
votes

use .prop not .attr

$me.prop('checked', true);

1
votes

Use prop() insead of attr() since you need to change the property here not the attribute :

$me.prop('checked', 'checked');

Hope this helps.

( Take a look to .prop() vs .attr() )

$('#box').on('change', 'input', function() {
  var $me = $(this);

  if (this.checked) {
    // Item has been checked, do nothing
  }
  else {
    // Item has been unchecked

    // Make sure it was not an accident
    var confirmReset = confirm("Reset checkbox?");

    if (confirmReset == true) {
      // Okay, reset
    }
    else {
      // Mistake, mark as checked again
      $me.prop('checked', 'checked');
      $me.addClass('shift-input');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
  <input type="checkbox" />
</div>