Earlier today I answered this question. The question is about toggling a class on a label element with jQuery. Consider the following HTML:
<label id="test">Test <input type="checkbox"></label>
And the following jQuery:
$("#test").click(function() {
$(this).toggleClass("testClass");
});
When I click on the label I would expect the testClass class to be applied to that element (as it doesn’t have that class when the page loads). However, nothing happens. See it for yourself here. I haven’t tried it in IE, but it doesn’t work correctly in Chrome or Firefox. I believe it will work in IE from the question linked to previously.
Stepping through the toggleClass method in the jQuery source, what seems to happen is the class gets added and removed again straight away.
If you move the input element outside of the label, the class is added as expected:
<label id="test" for="cb">Test</label>
<input type="checkbox" id="cb">
You can see that one in action here. So, my question is why does the first example not appear to add the class on the first click? Am I missing something blatantly obvious?
It looks like the problem stems from the fact that the
clickevent is being triggered twice (thus nullifying the toggle) when you have a nestedinputelement. I haven’t tested it on all browsers, but this seems to happen in FF8.Try clicking on the label in this example: http://jsfiddle.net/cRnJS/
Apparently, clicks on
labelelements triggers aclickevent on its associatedinput(which is why the check/uncheck works) and this event bubbles upwards hence triggering it a second time in the parentlabel.