views:

2491

answers:

7

I've used hover function where you do x on mouseover and y and mouseout, so I'm trying the same for click but it doesn't seem to work:

$('.offer').click(function(){ 
  $(this).find(':checkbox').attr('checked', true ); 
},function(){
  $(this).find(':checkbox').attr('checked', false ); 
});

I want the checkbox to be checked when clicked on a DIV, and unchecked if clicked again - a click toggle.

Thanks.

A: 

try changing this:

$(this).find(':checkbox').attr('checked', true );

to this:

$(this).find(':checkbox').attr('checked', 'checked');

Not 100% sure if that will do it, but I seem to recall having a similar problem. Good luck!

inkedmn
A: 
$('.offer').click(function(){ 
    if ($(this).find(':checkbox').is(':checked'))
    {
     $(this).find(':checkbox').attr('checked', false); 
    }else{
     $(this).find(':checkbox').attr('checked', true); 
    }
});
lod3n
+1  A: 

You could use the toggle function:

$('.offer').toggle(function() {
    $(this).find(':checkbox').attr('checked', true);
}, function() {
    $(this).find(':checkbox').attr('checked', false);
});
Marve
+12  A: 
 $('.offer').click(function(){ 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox.attr('checked'));
 });

or:

 $('.offer').click(function(){ 
       var $checkbox = $(this).find(':checkbox');
       $checkbox.attr('checked', !$checkbox.is(':checked'));
 });
karim79
Ooh, your way is better, upvoted.
lod3n
Perfect, thanks heaps!
Nimbuz
I wouldn't recommend setting an element's DOM attribute to a boolean value. Presumably it gets cast to the string `'1'` in the process.
Alex Barrett
@Alex Barrett - shouldn't matter, jQuery sweeps such details under the rug. I believe it's common practice to set boolean attributes like *selected*, *disabled* and *checked* to a boolean value using attr(). Furthermore, their internal representation is boolean, alert($foo.attr('checked')) will return true or false whether or not a string or a boolean has been used to set it.
karim79
A: 

In JQuery I don't think that click() accepts two functions for toggling. You should use the toggle() function for that: http://docs.jquery.com/Events/toggle

Kai
A: 
$('.offer').click(function() { 
    $(':checkbox', this).each(function() {
        this.checked = !this.checked;
    });
});
Alex Barrett