简体   繁体   中英

Make li select checkbox

I've got a script which checks a checkbox when the span of an li is clicked. My problem is that the width of the li is longer than the span and therefore, part of the li 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/

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.

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);
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM