I have a table of checkboxes. When I click a div with text “Select All” it should select all chekboxes and the div’s text needs to change to “Unselect all” irrespective of any check box is checked or not and vice versa.
I have written the following, it’s working fine, is there any better way to do it?
if($(this).text() == "Select All") {
$(this).text("Unselect All");
$.each($(".classname"),function(i ,ll){
$(this).attr('checked', true);
});
}else{
$(this).text("Select All");
$.each($(".classname"),function(i ,ll){
$(this).attr('checked', false);
});
}
thanks.
First of all,
$()is a function call so you should sayvar $this = $(this)if you’re going to be using$(this)a lot. Also, your$.eachloops are redundant as the jQuery objects apply their changes to all the matched elements anyway so looping is not needed (i.e. the jQuery methods are set based). You’re probably better off removing thecheckedattribute rather than setting it tofalsetoo. Something like this would probably be better: