Reputation: 85
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
Reputation: 1754
$('.list-item :checkbox').click(function () {
$(this).parent().toggleClass('selected');
});
Upvotes: 1
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
Reputation: 2879
$('.list-item input:checkbox').click(function() {
var selectedlistitem = $(this).parent('li');
selectedlistitem.toggleClass('selected');
});
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