Rick Schotte
Rick Schotte

Reputation: 1

cant check a checkbox a second time in jQuery

I'm trying to manupilate the input checkbox however everytime i click on the label the first time the checkbox will be selected after that i click the label again and the checkbox is unchecked so far so good. But when i click the label again the checkbox will not be checked.

My jQuery code is as followed

$('.form-checkbox label').on('click', function(e) {
    e.preventDefault();

        if ($(this).hasClass('checked')) {

            $(this).removeClass('checked');
            $(this).find('span').removeClass('checked');
            $(this).find('input').attr('CHECKED', false);
        } else {

            $(this).addClass('checked');
            $(this).find('span').addClass('checked');
            $(this).find('input').attr('CHECKED', true);
        }
    });

And my HTML is as followed

<div class="form-checkbox">
   <label id="checkbox-checkbox">
      <input id="checkbox-checkbox" name="checkbox" value="option1" type="checkbox" /><span></span> Option 1
   </label>
</div>

Upvotes: 0

Views: 279

Answers (2)

Pinkesh Sharma
Pinkesh Sharma

Reputation: 2456

I think you should try this

$('.form-checkbox label').on('click', function() {
   var chk = $("#checkbox-checkbox").prop("checked");
   $("#checkbox-checkbox").prop("checked", !chk);
});

Upvotes: 0

Satpal
Satpal

Reputation: 133453

Use .prop() instead of .attr()

 $(this).find('input').prop('checked', true/false);

See .prop() vs .attr()

Upvotes: 3

Related Questions