MrPizzaFace
MrPizzaFace

Reputation: 8086

jQuery is only working once? jsFiddle attached

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/

Upvotes: 0

Views: 35

Answers (1)

sberry
sberry

Reputation: 131978

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.

Upvotes: 3

Related Questions