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>
You’re overcomplicating things quite a bit, you just need to do this:
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 usingeach. Also,input:checkboxis redundant, all checkboxes are<input>s already so you just need:checkboxto find checkboxes.Inside the callback you can use
closestto go back up the DOM from the checkbox,this, to find the containing<li class="list-item">.