bob jomes
bob jomes

Reputation: 281

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/

Upvotes: 3

Views: 29488

Answers (2)

mentes
mentes

Reputation: 118

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

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

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.

Upvotes: 11

Related Questions