Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event triggering two times


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/

like image 309
Suresh Pattu Avatar asked Oct 30 '15 10:10

Suresh Pattu


People also ask

Why is click event fired twice?

The click event trigger twice because the event is bubbling. The code will works.

Can a button have multiple Onclicks?

Yes, You can call two or more function in one click, see the examples. Example One: <button onclick=”hello()”>Click Me</button> function hello() {

Why is this jquery Ajax click event firing multiple times?

an Event will fire multiple time when it is registered multiple times (even if to the same handler).


1 Answers

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

  1. It calls when label tag gets clicked
  2. event bubbles inside it and checkbox gets selected and checkbox bubbles the event to its parent node that is label tag again hence it is called twice.

To solve this, just attach the event handler to input/checkbox tag it should work fine.

like image 82
rajuGT Avatar answered Oct 09 '22 14:10

rajuGT