How to implement “select all” check box in HTML?

前端 未结 29 2877
悲哀的现实
悲哀的现实 2020-11-22 11:09

I have an HTML page with multiple checkboxes.

I need one more checkbox by the name \"select all\". When I select this checkbox all checkboxes in the HTML page must b

29条回答
  •  轮回少年
    2020-11-22 11:57

    Using jQuery and knockout:

    With this binding main checkbox stays in sync with underliying checkboxes, it will be unchecked unless all checkboxes checked.

    ko.bindingHandlers.allChecked = {
      init: function (element, valueAccessor) {
        var selector = valueAccessor();
    
        function getChecked () {
          element.checked = $(selector).toArray().every(function (checkbox) {
            return checkbox.checked;
          });
        }
    
        function setChecked (value) {
          $(selector).toArray().forEach(function (checkbox) {
            if (checkbox.checked !== value) {
              checkbox.click();
            }
          });
        }
    
        ko.utils.registerEventHandler(element, 'click', function (event) {
          setChecked(event.target.checked);
        });
    
        $(window.document).on('change', selector, getChecked);
    
        ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
          $(window.document).off('change', selector, getChecked);
        });
    
        getChecked();
      }
    };
    

    in html:

    
    
    
    

提交回复
热议问题