I am trying to run some function when clicking on the label text but the click event fired two times.
HTML
<label class="label_one">
Label One
<input type="checkbox"/>
</label>
But its not happening if I change the html code like this.
<label for="test" class="label_two">
Label Two
<input type="checkbox"/>
</label>
My script is this:
$('.label_one').click(function(){
console.log('testing');
});
Can anyone explain me why this is happening like this.
My jsfiddle is here check it ones.
https://jsfiddle.net/sureshpattu/hvv6ucu8/3/
The click event trigger twice because the event is bubbling. The code will works.
Yes, You can call two or more function in one click, see the examples. Example One: <button onclick=”hello()”>Click Me</button> function hello() {
an Event will fire multiple time when it is registered multiple times (even if to the same handler).
It is because of event bubbling.
In general all elements bubble the event to the root of the document whereas the label
tag will bubble the event to its child nodes and thats how the input tag is getting ticked when you click the label dom.
So in your case you attached the event handler to label tag so
label
tag again hence it is called twice.To solve this, just attach the event handler to input/checkbox tag it should work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With