Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click toggle with jQuery

I've used a hover function where you do x on mouseover and y and mouseout. 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 clicking on a div, and unchecked if clicked again - a click toggle.

like image 528
eozzy Avatar asked Sep 23 '09 16:09

eozzy


People also ask

What is toggle () in jQuery?

jQuery toggle() Method The toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden.

What is click toggle?

Definition of jQuery click toggle. The jQuery click toggle is performed to toggles the two or more functions executes on every click. We can perform the click toggle with the help of the toggle() function. The jQuery toggle() function is a built-in function in jQuery.

How do I toggle icons in jQuery?

click(function(){ $('#display_advance'). toggle('1000'); $(this).


1 Answers

This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:

 $(".offer").on("click", function () {         var $checkbox = $(this).find(':checkbox');        $checkbox.attr('checked', !$checkbox.attr('checked'));  }); 

or:

 $(".offer").on("click", function () {         var $checkbox = $(this).find(':checkbox');        $checkbox.attr('checked', !$checkbox.is(':checked'));  }); 

or, by directly manipulating the DOM 'checked' property (i.e. not using attr() to fetch the current state of the clicked checkbox):

 $(".offer").on("click", function () {         var $checkbox = $(this).find(':checkbox');        $checkbox.attr('checked', !$checkbox[0].checked);  }); 

...and so on.

Note: since jQuery 1.6, checkboxes should be set using prop not attr:

 $(".offer").on("click", function () {         var $checkbox = $(this).find(':checkbox');        $checkbox.prop('checked', !$checkbox[0].checked);  }); 
like image 197
karim79 Avatar answered Oct 11 '22 17:10

karim79