码迷,mamicode.com
首页 > 其他好文 > 详细

Select/Deselect All Checkboxes

时间:2015-11-03 17:22:11      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

Using jQuery:

<div>
    <input type="checkbox" id="SelectAll" />check all<br />
    <input type="checkbox" name="sub" />1<br />
    <input type="checkbox" name="sub" />2<br />
    <input type="checkbox" name="sub" />3<br />
    <input type="checkbox" name="sub" />4<br />
</div> 
$("#SelectAll").click(function () {
            $("input[name=‘sub‘]").prop("checked", this.checked);
        });

        $("input[name=‘sub‘]").click(function () {
            var $subs = $("input[name=‘sub‘]");
            $("#SelectAll").prop("checked", $subs.length == $subs.filter(":checked").length ? true : false);
        });

Using Knockout:

<div>
    <input type="checkbox" data-bind="checked: SelectAll" />check all<br />
    <!-- ko foreach: $data.Items -->
    <input type="checkbox" data-bind="checked: Selected" /><!-- ko text: Id --> <!-- /ko --> <br />
    <!-- /ko -->
</div> 
        function ViewModel() {
            var self = this;

            self.Items = ko.observableArray([new Item(1), new Item(2), new Item(3), new Item(4)]);
            self.SelectAll = ko.pureComputed({
                read: function () {
                    var obj = ko.utils.arrayFirst(self.Items(), function (_item) {
                        return !_item.Selected();
                    });
                    return obj == null;
                },
                write: function (value) {
                    ko.utils.arrayForEach(self.Items(), function (_item) {
                        _item.Selected(value);
                    });
                }
            });
        }

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

        ko.applyBindings(new ViewModel());

With using Knockout, you should note these:

1.Virtual DOM elements bindings

2.Utility functions in Knockout

Reference:

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

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

 

Select/Deselect All Checkboxes

标签:

原文地址:http://www.cnblogs.com/laixiancai/p/4933666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!