Double tap event trigger


I try to run some functions when I click on the label text, but the click event fires twice.
HTML

<label class="label_one"> Label One <input type="checkbox"/> </label> 

But this does not happen if I change the html code as follows.

 <label for="test" class="label_two"> Label Two <input type="checkbox"/> </label> 

My script:

 $('.label_one').click(function(){ console.log('testing'); }); 

Can someone explain to me why this is happening like this.
My jsfiddle is here, check it out.
https://jsfiddle.net/sureshpattu/hvv6ucu8/3/

+5
source share
5 answers

It is because of the bubble of events .

In general, all elements bubble an event to the root of the document, while the label tag bubbles an event with its child nodes , and this is how the input tag flows when you click label dom.

So, in your case, you attached an event handler to the tag tag , so

  • It calls up when you click the tag label
  • event bubbles inside it and the checkbox is set, and the checkbox places the event in the parent node, i.e. label tag, so it is called twice.

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

+5
source

I could not reproduce this in the chrome version that I am using.

But if you come across this in some browser, probably because -

According to the specification, labels containing inputs and those that are connected to the input through the for attribute cause a click on the corresponding input when pressed.

So, in your first case there are 2 click events:

  • Actual click on <label>
  • Press the <input> button by pressing the button

What fires on <input> will bubble up to <label> and fire your handler.

In the second case, since the for attribute is specified and there is no corresponding input with id in 'test', an additional click does not start even if the input is inside the label.

+3
source

Click checkbox Click on the label . Try using .change event in input

 $('.label_one input').change(function(){ var html = '<div class="log_sec_one">Log</div>'; $('.logs').append(html); }); $('.label_two input').change(function(){ var html = '<div class="log_sec_two">Log</div>'; $('.logs').append(html); }); 

Demo

+2
source

Move your entry outside of your label and use the for="" attribute.

 <label class="label_one" for="checkbox_one"> Label One </label> <input type="checkbox" id="checkbox_one" /> <br/><br/> <label for="checkbox_two" class="label_two"> Label Two </label> <input type="checkbox" id="checkbox_two"/> <div class="logs"></div> 

JSFiddle: https://jsfiddle.net/hvv6ucu8/2/

0
source
 <label for="text" class="label_one"> Label One <input type="checkbox"/> </label> <br/><br/> <label for="text" class="label_two"> Label Two <input type="checkbox" name="1"/> </label> 

You forgot to specify the attribute in label (label_one). just change it. he will work

0
source

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


All Articles