Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery click event triggers twice when clicked on html label

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>&nbsp;</td>     <td>&nbsp;</td> </tr> 

JQUERY

$(document).ready(function () {      $('#test label').live('click', function (event) {         alert('clicked');     });       $('#test checkbox').live('click', function (event) {         alert('clicked');     });  }); 
like image 338
sravis Avatar asked Jun 19 '13 07:06

sravis


Video Answer


1 Answers

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');     } }); 
like image 104
t.niese Avatar answered Oct 12 '22 06:10

t.niese