Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple click on labels makes double click

I have a label and some functions running while clicking on it.

But when a click event is made, a double click event is done, then my functions run 2 times...

You can see a light example here

HTML:

<label>
<input type="checkbox" id="checkbox"> Click here
</label>
<input type="text" id="test" value="0"/> clicks​​​

JavaScript:

$(document).ready(function(){
    $('label').click(function(event) {
         $('#test').val(parseInt($('#test').val())+1);
         event.preventdefault();
    });
});​
  • When we click on the checkbox, the clicks counter is +1 >> Ok
  • When we click on the label, the clicks counter is +2 >> Nok

How to solve this problem ?

Edit

preventdefault() to preventDefault() fixed the double click, but now checkbox is not checked anymore...

like image 331
Valky Avatar asked May 30 '12 15:05

Valky


People also ask

How do you stop a single click event when double clicking?

on('click',function(e){ if(e. originalEvent. detail > 1){ return; /* if you are returning a value from this function then return false or cancel the event some other way */ } }); Done.

How do I stop multiple clicks on a button?

To prevent multiple button clicks in React: Set an onClick prop on the button, passing it a function. When the button gets clicked, set its disabled attribute to true .

What is clicking and double clicking?

Typically, a single click initiates a user interface action and a double-click extends the action. For example, one click usually selects an item, and a double-click edits the selected item.


2 Answers

Well this is interesting. You're seeing two click events, one of them from the checkbox input, and the other (of course) from the label. And it makes sense: Clicking a label is like clicking the checkbox the label labels, by design. Here's an updated fiddle showing what's happening.

So just hook click on the checkbox and don't hook it on the label:

$(document).ready(function(){
    $('#checkbox').click(function(event) {
        $('#test').val(parseInt($('#test').val())+1);
    });
});​

Updated fiddle


And as Rocket said in the question's comments: preventDefault has a capital D in it, so your code was throwing an exception. But you didn't want preventDefault anyway, because you want the checkbox to be checked.

like image 111
T.J. Crowder Avatar answered Oct 02 '22 19:10

T.J. Crowder


A simple workaround is to ignore one of the call.. See below,

$(document).ready(function(){   
    $('label').click(function(event) {
        if (event.target.nodeName == 'LABEL') return;
        $('#test').val(parseInt($('#test').val())+1);         
    });
});

DEMO

like image 22
Selvakumar Arumugam Avatar answered Oct 02 '22 18:10

Selvakumar Arumugam