Strange toggleClass behavior with label element

Earlier today I answered this question . The question is switching the class to the label element using 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 expect the testClass class testClass be applied to this element (since it does not have this class when loading the page). However, nothing happens. Look at it here . I have not tried it in IE, but it does not work correctly in Chrome or Firefox. I believe that it will work in IE from a question related to earlier.

By executing the toggleClass method in the jQuery source , it seems that the class is being added and removed again.

If you move the input element outside the label , the class is added as expected:

 <label id="test" for="cb">Test</label> <input type="checkbox" id="cb"> 

You can see it in action here . So my question is: why doesn't the first example appear to add a class on first click? Did I miss something obviously obvious?

+4
source share
1 answer

It seems like the problem is that the click event is fired twice (thus invalidating the switch) when you have a nested input element. I have not tested it in all browsers, but it is similar to FF8.

Try clicking on the label in this example: http://jsfiddle.net/cRnJS/

Apparently, clicking on the label elements triggers a click event in its associated input (therefore checking / unchecking the box works), and this event bubbles up, therefore, it fires a second time in the parent label ,

+4
source

Source: https://habr.com/ru/post/1384710/


All Articles