I have a form with checkboxes and then text to the right of the checkbox. There are jquery events attached to the click events of the the checkbox. What I want is to allow the user to click on the label or the checkbox and have the checkbox check/uncheck and the event to fire. Below is a simplified version of what I'm trying to do (DON'T run the code as below as it creates an endless loop).
<script>
$(document).ready(function() {
$("form p").click(function() {
$(this).find("input").click();
});
$("form input").click(function() {
alert("clicked");
});
});
</script>
<form>
<p> <input type="checkbox" name="checker" value="1" /> Click anywhere</p>
<p> <input type="checkbox" name="checker2" value="2" /> Click anywhere</p>
</form>
I have a form with checkboxes and then text to the right of the checkbox. There are jquery events attached to the click events of the the checkbox. What I want is to allow the user to click on the label or the checkbox and have the checkbox check/uncheck and the event to fire. Below is a simplified version of what I'm trying to do (DON'T run the code as below as it creates an endless loop).
<script>
$(document).ready(function() {
$("form p").click(function() {
$(this).find("input").click();
});
$("form input").click(function() {
alert("clicked");
});
});
</script>
<form>
<p> <input type="checkbox" name="checker" value="1" /> Click anywhere</p>
<p> <input type="checkbox" name="checker2" value="2" /> Click anywhere</p>
</form>
Share
Improve this question
asked Jan 18, 2009 at 22:46
Brian FisherBrian Fisher
24k15 gold badges80 silver badges82 bronze badges
3 Answers
Reset to default 5Use the LABEL tag: http://www.w3schools./tags/tag_label.asp
clicking on any <input>
tag triggers the click event of <p>
tag (because <input>
tag is inside the <p>
tag) which then triggers the click event of <input>
tag leading to an endless loop.
You can prevent the 'endless loop' using jQuery's event.stopPropagation method.