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…
Well this is interesting. You’re seeing two
clickevents, one of them from the checkboxinput, and the other (of course) from thelabel. And it makes sense: Clicking alabelis like clicking the checkbox thelabellabels, by design. Here’s an updated fiddle showing what’s happening.So just hook
clickon the checkbox and don’t hook it on the label:Updated fiddle
And as Rocket said in the question’s comments:
preventDefaulthas a capitalDin it, so your code was throwing an exception. But you didn’t wantpreventDefaultanyway, because you want the checkbox to be checked.