I have an div container which contains html checkbox and its label. Using jquery i wanted to trigger an click event when someone clicks on label in this container.
I see that jquery click event triggers twice when i click on label!
For testing purpose i triggered click event on checkbox instead of label and here checkbox click event triggers only once as it should be.
Here is the fiddle. http://jsfiddle.net/AnNvJ/2/
<tr> <td> <div id="test"> <label> <input type="checkbox" id="1" />demo1</label> <label> <input type="checkbox" id="2" />demo2</label> <label> <input type="checkbox" id="3" />demo3</label> </div> </td> <td> </td> <td> </td> </tr>
JQUERY
$(document).ready(function () { $('#test label').live('click', function (event) { alert('clicked'); }); $('#test checkbox').live('click', function (event) { alert('clicked'); }); });
The one of $('#test checkbox')
is never called, because you don't have a tag with name checkbox
.
And depending if you click on checkbox or the label, the callback for $('#test label')
is called once or twice cause of the bubbling because the input element is part of the label and is one union and therefore also received the event if the label is click (it is not bubbling, you can't do event.stopPropagation()
).
You can check this if you change your code this way:
$('#test label').live('click', function (event) { event.stopPropagation(); //<-- has no effect to the described behavior console.log(event.target.tagName); });
Click on label:
LABEL
INPUT
Click on input:
INPUT
EDIT If you only want to handle the click on the label
and not the checkbox - and you can't change your HTML structure - you can just ignore the event of the input
element.
Either this way:
$('#test label').live('click', function (event) { if( event.target.tagName === "LABEL" ) { alert('clicked'); } });
Or using jQuery to test:
$('#test label').live('click', function (event) { if( $(event.target).is("label") ) { alert('clicked'); } });
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