Make li select checkbox
21,787
Solution 1
Use the appropriate HTML <label>
element to associate the text with the <input>
:
<ul class="myclass">
<li><label><input type="checkbox"><span>some text</span></label></li>
<li><label><input type="checkbox"><span>some text</span></label></li>
<li><label><input type="checkbox"><span>some text</span></label></li>
</ul>
With display: block;
(for the <label>
element's style) to fill its ancestor <li>
and the desired behaviour is automatic, requiring no JavaScript.
Solution 2
if i got the question right you can do this
$('ul.myclass li').click( function() {
var $cb = $(this).find(":checkbox");
if (!$cb.prop("checked")) {
$cb.prop("checked", true);
} else {
$cb.prop("checked", false);
}
});
Author by
bob jomes
Updated on December 30, 2020Comments
-
bob jomes over 3 years
I've got a script which checks a checkbox when the
span
of anli
is clicked. My problem is that the width of theli
is longer than thespan
and therefore, part of theli
doesn't check the checkbox.$('ul.myclass li span').click( function() { var $cb = $(this).parent().find(":checkbox"); if (!$cb.prop("checked")) { $cb.prop("checked", true); } else { $cb.prop("checked", false); } });
.myclass li span { margin-left: 5px; } li { background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="myclass"> <li><input type="checkbox"><span>some text</span></li> <li><input type="checkbox"><span>some text</span></li> <li><input type="checkbox"><span>some text</span></li> </ul>
JsFiddle: http://jsfiddle.net/7w82S/89/
-
bob jomes about 8 yearsSay I had to have the label after the
input
... would it still require no Javascript? -
Sikshya Maharjan about 8 yearsFor the whole
<li>
to be clickable, with the<label>
after the check-box (in the HTML) that would require JavaScript. If you could leave the check-box within the<label>
, but position it before, or after, using CSS then it would still work with the above approach. -
bob jomes about 8 yearshmm... could i have two
labels
in theli
? -
Sikshya Maharjan about 8 yearsYou could, so long as they're not nested; but instead of asking further questions in comments why not edit your question to include the desired end result, or the requirements under which you're working? If the HTML has to be in a specific order, or structure, show that. If it's to achieve a specific visual look, or aesthetic, show that (using an image). Currently while I can answer each of your questions as you ask them I'm not sure I'm giving you the best advice without knowing the required end-result.