0

I want to be able to check and uncheck a checkbox by clicking its parent DIV.

html:

<div class="insurance-option-select">
    <input name="insurance[Auto]" type="checkbox" value="1">
</div>
<div class="insurance-option-select">
    <input name="insurance[Home]" type="checkbox" value="2">
</div>

js:

  $('.insurance-option-select').on('click', function () {
      if ($(this).find('input').prop('checked')) {
          $(this).find('input').removeAttr('checked');
      } else {
          $(this).find('input').attr('checked', true);
      }
  });

css:

.insurance-option-select {
    background: red;
    padding: 30px;
    margin: 30px auto;
}
.insurance-option-select:hover {
    background: green;
}

Problem is it only works once. http://jsfiddle.net/zbh691y0/

MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123
  • possible duplicate of [.prop() vs .attr()](http://stackoverflow.com/questions/5874652/prop-vs-attr) –  Sep 10 '14 at 00:14

1 Answers1

3

Just use prop the whole time, not attr and prop.

http://jsfiddle.net/zbh691y0/1/

$('.insurance-option-select').on('click', function () {
    if ($(this).find('input').prop('checked')) {
        $(this).find('input').prop('checked', false);
    } else {
        $(this).find('input').prop('checked', true);
    }
});

This can also be simplified by doing:

$('.insurance-option-select').on('click', function () {
    cb = $(this).find('input')
    cb.prop('checked', ! cb.prop('checked'))
});

The property checked is a boolean. As such, you can negate it's value by using a !. Imagine instead this code:

   cb = $(this).find('input') 
   is_checked = cb.prop('checked')  // This will be true if it is checked, and false if not
   inverse_is_checked = ! is_checked // This will be the opposite of is_checked
   cb.prop('checked', inverse_is_checked) // Now you set the checked property value to the inverse of what it was originally

But that can be done in the one line, like shown above.

sberry
  • 128,281
  • 18
  • 138
  • 165
  • Where can I get info or could you please explain how this line works? `cb.prop('checked', ! cb.prop('checked'))` – MrPizzaFace Sep 10 '14 at 00:07
  • They are different things, and since you never change `prop('checked')` your if statement will always be true. Read here for more info: http://stackoverflow.com/questions/5874652/prop-vs-attr – sberry Sep 10 '14 at 00:08
  • @f1f5. See edit for explanation of the simplification. – sberry Sep 10 '14 at 00:08