I am trying to run some function when clicking on the label text but the click event fired two times.
HTML
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.
<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 put for attribute in label (label_one). just change that. it will work
I couldn't reproduce this in the version of chrome that I'm using.
But if you're facing this in some browser, it's likely because -
According to spec, labels containing inputs, and the ones connected to an input via for
attribute trigger a click on the associated input when they are clicked.
So in your first case, there are 2 click events:
<label>
<input>
by the labelThe one triggered on <input>
will bubble up to <label>
and trigger your handler.
In the second case, Since a for
attribute is specified and there is no matching input with id
of 'test', the additional click is not triggered even if the input is inside the label.
Click on checkbox
do click on label
. Try use .change
event on 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
Move your input 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/