问题
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.
回答1:
You don't need a script. You can wrap the checkbox and all the li
content with the label
. Give the label display:block
so it will "take" the full width of the li
, in this way, the li
will 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>
回答2:
Just try this;
Add class="myclass" to ul.
$('ul.myclass li input').click(
function(event){
event.stopPropagation();
});
回答3:
My solution does use straight up JS but it's inline in the HTML, so nothing too complicated.
<li onclick="document.getElementById('a1').checked = !document.getElementById('a1').checked;">
<input id="a1" type="checkbox" onclick="event.stopPropagation();"><label for="a1">1</label>
</li>
See here: https://jsfiddle.net/Delorian/2v47Lwhb/
回答4:
- use event.preventDefault() on the click event of the label.
- And then use the css property z-index:2 on the checkbox input so that the checkbox is in on top of the label layer.
来源:https://stackoverflow.com/questions/36996999/cant-check-checkbox-on-clicking-li