Is there any way to optimize the following checkbox select/unselect code
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.
I'm assuming classname
is a class of the concerned checkboxes. You can try:
if($(this).text().trim() == "Select All") {
$(this).text("Unselect All");
$(".classname").attr('checked', true);
}else{
$(this).text("Select All");
$(".classname").attr('checked', false);
}
First of all, $()
is a function call so you should say var $this = $(this)
if you're going to be using $(this)
a lot. Also, your $.each
loops 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 the checked
attribute rather than setting it to false
too. Something like this would probably be better:
var $this = $(this);
if($this.text() == 'Select All') {
$this.text('Unselect All');
$('.classname').attr('checked', true);
}
else {
$this.text('Select All');
$('.classname').removeAttr('checked');
}
精彩评论