I'm trying to check a checkbox by clicking a li. The problem is, the checkbox is only checked when someone clicks on the label, not the full li (this is because the width of the li is longer than the label!
<ul>
<li><input id="a1" type="checkbox"><label for="a1">1</label></li>
<li><input id="a2" type="checkbox"><label for="a2">2</label></li>
<li><input id="a3" type="checkbox"><label for="a3">3</label></li>
</ul>
I have tried to solve this problem using the Javascript below, however it still only checks the checkbox when the label is clicked.
$("li").click(function(e) {
var checked = !$(this).children("input").first().prop("checked");
$(this).children("input").first().prop("checked", checked);
$(this).toggleClass("selected", checked);
});
Note: if possible, I would like to avoid Javascript and Jquery.
You don't need a script. You can wrap the checkbox and all the li content with label. Give the label display:block so it will take the full width of the li. This way, the li will be clickable (like, not really)
label {
display:block;
}
<ul>
<li><label for="a1"><input id="a1" type="checkbox">1</label></li>
<li><label for="a2"><input id="a2" type="checkbox">2</label></li>
<li><label for="a3"><input id="a3" type="checkbox">3</label></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With