Select/DeselectAllCheckboxes

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Code share time! The following demo is about how to select/deselect all checkboxes, like this,

Using jQuery:

<div><inputtype="checkbox"id="SelectAll"/>check all<

br/><inputtype="checkbox"name="sub"/>1<

br/><inputtype="checkbox"name="sub"/>2<

br/><inputtype="checkbox"name="sub"/>3<

br/><inputtype="checkbox"name="sub"/>4<

br/></div>

var$SelectAll = $("#SelectAll");var$Sub = $("input[name='sub']");

$SelectAll.click(function() {

$Sub.PRop("checked",this.checked);

});

$Sub.click(function() {

$SelectAll.prop("checked", $Sub.length == $Sub.filter(":checked").length ?true:false);

});

How about turning it into a jQuery plugin:

(function($) {

$.fn.selectAndDeselectAllSubCheckboxes=function(options) {if(options == undefined || options.SubCheckboxesName ==undefined) {

alert("Parameters configuration error.");return;

}if(options.SubCheckboxesName ==null|| options.SubCheckboxesName == "") {

alert("you must assign parameter 'SubCheckboxesName' value.");return;

}vardefaultVal ={

SubCheckboxesName:""};varobj =$.extend(defaultVal, options);var$this=this;var$Sub = $("input[name='" + obj.SubCheckboxesName + "']");

$this.click(function() {

$Sub.prop("checked",this.checked);

});

$Sub.click(function() {

$this.prop("checked", $Sub.length == $Sub.filter(":checked").length ?true:false);

});

}

})(jQuery);

then use the plugin:

$("#SelectAll").selectAndDeselectAllSubCheckboxes({ SubCheckboxesName: "sub" });

Using Knockout:

<div><inputtype="checkbox"data-bind="checked: SelectAll"/>check all<

br/><!--ko foreach: $data.Items--><inputtype="checkbox"data-bind="checked: Selected"/><!--ko text: Id--><!--/ko--><

br/><!--/ko--></div>

functionViewModel() {varself =this;

self.Items= ko.observableArray([newItem(1),newItem(2),newItem(3),newItem(4)]);

self.SelectAll=ko.pureComputed({

read:function() {varobj = ko.utils.arrayFirst(self.Items(),function(_item) {return!_item.Selected();

});returnobj ==null;

},

write:function(value) {

ko.utils.arrayForEach(self.Items(),function(_item) {

_item.Selected(value);

});

}

});

}varItem =function(id) {this.Id =id;this.Selected = ko.observable(false);

}

ko.applyBindings(newViewModel());

With using Knockout, you should note these:

1.Virtual DOM elements bindings

2.Utility functions in Knockout

You can also view the codes in GitHub:

https://github.com/laixiancai/javascriptLab/blob/master/Webapplication1/Views/JQueryDemo/CheckAll.cshtml

https://github.com/laixiancai/JavascriptLab/blob/master/WebApplication1/Views/KnockoutDemo/CheckAll.cshtml

Reference:

http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html

https://visualstudiomagazine.com/articles/2013/09/01/essential-knockoutjs-part-2.aspx

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航