user416803
user416803

Reputation: 85

JQuery Selected Checkbox Item Background Color

I've got the code below "working" but I can't figure out how to get the click event to be just for the checkbox. Right now just click the li will toggle my background color...I'm totally missing something here. All I need is that for each li that has a checkbox checked the bg color will change and when unchecked it will return to it's previous color. Can anyone help me out.

<script type="text/javascript">

$(document).ready(function() {
    $('.list-item').find('input:checkbox').each(function(index) {
        var selectedlistitem = $('.list-item');
        $(selectedlistitem).click(function () {                     
            $(this).toggleClass('selected');
        });
    });
});
</script>


<ul> class="list-item-container">
<li class="list-item"><input type="checkbox" />Item 1</li>
<li class="list-item"><input type="checkbox" />Item 2</li>
<li class="list-item"><input type="checkbox" />Item 3</li>
</ul>

Upvotes: 0

Views: 609

Answers (3)

Simon
Simon

Reputation: 1754

$('.list-item :checkbox').click(function () {
    $(this).parent().toggleClass('selected');
});

Upvotes: 1

mu is too short
mu is too short

Reputation: 434865

You're overcomplicating things quite a bit, you just need to do this:

$('.list-item :checkbox').click(function() {
    $(this).closest('.list-item').toggleClass('selected');
});

Demo: http://jsfiddle.net/ambiguous/ddkD9/

You don't need $().find().each(), you can flatten your $().find() into a single selector and jQuery functions are (almost always) set-based already so there's no need for iteration using each. Also, input:checkbox is redundant, all checkboxes are <input>s already so you just need :checkbox to find checkboxes.

Inside the callback you can use closest to go back up the DOM from the checkbox, this, to find the containing <li class="list-item">.

Upvotes: 3

Justice Erolin
Justice Erolin

Reputation: 2879

$('.list-item input:checkbox').click(function() {
    var selectedlistitem = $(this).parent('li');
    selectedlistitem.toggleClass('selected');
});

http://jsfiddle.net/3s2pk/

You dont need to do the each function, and within each one should refer to the clicked element itself, and not do a global selector.

Upvotes: 1

Related Questions