0

I'm having some trouble using JQuery to check and uncheck an input. I know that .prop is the proper way to do it, but it doesn't seem to be working for me. Here's my code:

HTML:

<div class="checkwrap"><input name="mentoringType" type="checkbox" checked="false" value="test">test</div>

JS:

$('.checkwrap').click(function() {
    if ($(this).find('input').is(':checked')){
        $(this).toggleClass('checkwrap-active').find('input').filter(':checkbox').prop('checked',false);
    } else {
        $(this).toggleClass('checkwrap-active').find('input').filter(':checkbox').prop('checked',true);
    }
});

The input is wrapped for styling purposes. If I use .attr('checked',true/false) instead, then it works to change the checked property to checked, but it does not uncheck. What's going on?

  • 2
    Why don't you use a [label](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) instead of a `div`? You wouldn't need any javascript then. – Eggplant Nov 07 '15 at 10:40
  • 1
    By the way, `.prop()` is actually the proper way, but your example doesn't work because you don't have to assing a value to the `checked` property. It is a boolean *property* indeed, not an *attribute*, thus `checked` is enough, dropping the `="false"` part. – Eggplant Nov 07 '15 at 10:44
  • Possible duplicate of [Checking a checkbox with jQuery?](http://stackoverflow.com/questions/426258/checking-a-checkbox-with-jquery) – Michael Doye Nov 07 '15 at 10:51
  • Your code works as expected even it is not the way you should do it: http://jsfiddle.net/qa50vmdt/ Ya, use a label – A. Wolff Nov 07 '15 at 10:52

1 Answers1

0

Eggplant is right: you should use a lebel element to make "test" clickable.

To answer your question: Your skript does work, when only the text ist clicked.

It also works, but not as expected, when the checkbox is clicked. In this case your code leads to a duplication of the ation executed, because the click event bubbles up the DOM tree.

If the checkbox is not selected, a click on it makes it being selected and your code comes in, detects it as being selected and unselects it again.

For an unselected box it works vice versa.

But as stated before: you should have chosen a label in the first place.

Stefan Dochow
  • 1,454
  • 1
  • 10
  • 11