0

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>
Indaleco
  • 49
  • 1
  • 5
  • ...and is this working or not? – Leeish Aug 11 '13 at 02:51
  • As of jQuery 1.7, the correct method for all boolean attributes is `.prop()` rather than `.attr()`. – DevlshOne Aug 11 '13 at 02:52
  • Please supply some HTML markup for further clarification of your issue. – DevlshOne Aug 11 '13 at 02:53
  • @DevlshOne As of 1.6, actually. And `.prop()` is not just for "boolean", but all DOM element properties. @ OP this thread will give you more insight on when to use `prop` and `attr`: http://stackoverflow.com/questions/5874652/prop-vs-attr – Fabrício Matté Aug 11 '13 at 03:02

1 Answers1

1

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531