jQuery Click fires twice when clicking on label
I tried adding the solution above by adding:
evt.stopPropagation();
evt.preventDefault();
but didn't work. However adding this:
evt.stopImmediatePropagation();
solved the problem! :)
Try adding:
evt.stopPropagation();
evt.preventDefault();
to the .bind() or .click(), whichever you're seeing. Also, add the parameter evt
to the function, like function(evt) {...
Bind the click event to the input rather than the label. When the label is clicked - the event will still occur because, as Dustin mentioned, a click on the label triggers a click on the input. This will allow the label to hold its normal functionality.
$('input').click();
Instead of
$('label').click();
If you're trying to use an outer container as a click element you can also let the events bubble naturally and test for the expected element in your click handler. This scenario is useful if you're trying to style a unique click zone for a form.
<form>
<div id="outer">
<label for="mycheckbox">My Checkbox</label>
<input type="checkbox" name="mycheckbox" id="mycheckbox" value="on"/>
</div>
</form>
<script>
$('#outer').on('click', function(e){
// this fires for #outer, label, and input
if (e.target.tagName == 'INPUT'){
// only interested in input
console.log(this);
}
});
</script>
To fix this the easy way, remove the "for" attribute on the label. A click on the label will also trigger a click on the associated element. (which in your case is firing your click event twice.)
Good luck