Reputation: 49
So I've been researching for a while, and I'm kind of stumped. What I'm doing is pulling data from a database and putting it into rows of divs. What I want to do is make the div "clickable" and have the background color change when clicked. I will have a hidden checkbox element that will be toggled. Here is the code I've been able to find to assist me so far.
What I need to do is figure out where to add a function that toggles the class whether the checkbox is checked or not.
Jquery
$('.item').click(function(){
$('.item').toggle(
function(event) {
$(this).find('input').attr('checked', true);
},
function(event) {
$(this).find('input').attr('checked', false);
}
);
});
HTML
<div class="item">
stuff here
<input type="checkbox" class="hidden" name="item1" value"true">
</div>
<div class="item">
stuff here
<input type="checkbox" class="hidden" name="item2" value"true">
</div>
Upvotes: 0
Views: 3989
Reputation: 388316
Try
$('.item').click(function(){
var $this = $(this), $chk = $this.find('input:checkbox'), checked = $chk.is(':checked');
$chk.prop('checked', !checked);
$this.toggleClass('checked', !checked);
});
Demo: Fiddle
Upvotes: 1