如何实现“全选” HTML 中的复选框?

发布于 2024-07-10 07:30:03 字数 103 浏览 9 评论 0原文

我有一个带有多个复选框的 HTML 页面。

我还需要一个名为“全选”的复选框。 当我选择此复选框时,必须选择 HTML 页面中的所有复选框。 我怎样才能做到这一点?

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 be selected. How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

鹤舞 2024-07-17 07:30:04

演示 http://jsfiddle.net/H37cb/

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>

<script type="text/javascript">
$(document).ready(function(){

$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});

});
</script>




<div id="wrapper">
 <li style="margin-top: 20px">
  <input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
  <ul>
   <li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
     <li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
     <li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
     <li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
    </ul>
   </li>
  </ul>
  <ul>
   <li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
     <li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
     <li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
    </ul>
   </li>
  </ul>
 </li>
</div>

Demo http://jsfiddle.net/H37cb/

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>

<script type="text/javascript">
$(document).ready(function(){

$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});

});
</script>




<div id="wrapper">
 <li style="margin-top: 20px">
  <input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
  <ul>
   <li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
     <li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
     <li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
     <li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
    </ul>
   </li>
  </ul>
  <ul>
   <li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
     <li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
     <li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
    </ul>
   </li>
  </ul>
 </li>
</div>
朱染 2024-07-17 07:30:04

当您调用document.getElementsByName("name")时,您将获得一个Object。 使用 .item(index) 遍历 Object

HTML 的所有项目:

<input type="checkbox" onclick="for(c in document.getElementsByName('rfile')) document.getElementsByName('rfile').item(c).checked = this.checked">

<input type=​"checkbox" name=​"rfile" value=​"/​cgi-bin/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​includes/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​misc/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​modules/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​profiles/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​scripts/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​sites/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​stats/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​themes/​">​

When you call document.getElementsByName("name"), you will get a Object. Use .item(index) to traverse all items of a Object

HTML:

<input type="checkbox" onclick="for(c in document.getElementsByName('rfile')) document.getElementsByName('rfile').item(c).checked = this.checked">

<input type=​"checkbox" name=​"rfile" value=​"/​cgi-bin/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​includes/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​misc/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​modules/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​profiles/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​scripts/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​sites/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​stats/​">​
<input type=​"checkbox" name=​"rfile" value=​"/​themes/​">​
〃安静 2024-07-17 07:30:04

稍微改变的版本,尊重地检查和取消检查

$('#select-all').click(function(event) {
        var $that = $(this);
        $(':checkbox').each(function() {
            this.checked = $that.is(':checked');
        });
    });

Slightly changed version which checks and unchecks respectfully

$('#select-all').click(function(event) {
        var $that = $(this);
        $(':checkbox').each(function() {
            this.checked = $that.is(':checked');
        });
    });
苏别ゝ 2024-07-17 07:30:04

我的简单解决方案允许有选择地选择/取消选择表单给定部分中的所有复选框,同时为每个复选框使用不同的名称,以便在表单已发布。

Javascript:

function setAllCheckboxes(divId, sourceCheckbox) {
    divElement = document.getElementById(divId);
    inputElements = divElement.getElementsByTagName('input');
    for (i = 0; i < inputElements.length; i++) {
        if (inputElements[i].type != 'checkbox')
            continue;
        inputElements[i].checked = sourceCheckbox.checked;
    }
}

HTML 示例:

<p><input onClick="setAllCheckboxes('actors', this);" type="checkbox" />All of them</p>
<div id="actors">
    <p><input type="checkbox" name="kevin" />Spacey, Kevin</p>
    <p><input type="checkbox" name="colin" />Firth, Colin</p>
    <p><input type="checkbox" name="scarlett" />Johansson, Scarlett</p>
</div>

希望您喜欢!

My simple solution allows to selectively select/deselect all checkboxes in a given portion of the form, while using different names for each checkbox, so that they can be easily recognized after the form is POSTed.

Javascript:

function setAllCheckboxes(divId, sourceCheckbox) {
    divElement = document.getElementById(divId);
    inputElements = divElement.getElementsByTagName('input');
    for (i = 0; i < inputElements.length; i++) {
        if (inputElements[i].type != 'checkbox')
            continue;
        inputElements[i].checked = sourceCheckbox.checked;
    }
}

HTML example:

<p><input onClick="setAllCheckboxes('actors', this);" type="checkbox" />All of them</p>
<div id="actors">
    <p><input type="checkbox" name="kevin" />Spacey, Kevin</p>
    <p><input type="checkbox" name="colin" />Firth, Colin</p>
    <p><input type="checkbox" name="scarlett" />Johansson, Scarlett</p>
</div>

I hope you like it!

︶ ̄淡然 2024-07-17 07:30:04
<html>

<head>
<script type="text/javascript">

    function do_this(){

        var checkboxes = document.getElementsByName('approve[]');
        var button = document.getElementById('toggle');

        if(button.value == 'select'){
            for (var i in checkboxes){
                checkboxes[i].checked = 'FALSE';
            }
            button.value = 'deselect'
        }else{
            for (var i in checkboxes){
                checkboxes[i].checked = '';
            }
            button.value = 'select';
        }
    }
</script>
</head>

<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />

<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>

</html>
<html>

<head>
<script type="text/javascript">

    function do_this(){

        var checkboxes = document.getElementsByName('approve[]');
        var button = document.getElementById('toggle');

        if(button.value == 'select'){
            for (var i in checkboxes){
                checkboxes[i].checked = 'FALSE';
            }
            button.value = 'deselect'
        }else{
            for (var i in checkboxes){
                checkboxes[i].checked = '';
            }
            button.value = 'select';
        }
    }
</script>
</head>

<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />

<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>

</html>
风为裳 2024-07-17 07:30:04

尝试这个简单的 JQuery:

$('#select-all').click(function(event) {
  if (this.checked) {
    $(':checkbox').prop('checked', true);
  } else {
    $(':checkbox').prop('checked', false);
  }
});

Try this simple JQuery:

$('#select-all').click(function(event) {
  if (this.checked) {
    $(':checkbox').prop('checked', true);
  } else {
    $(':checkbox').prop('checked', false);
  }
});
酷炫老祖宗 2024-07-17 07:30:04

这相当简单:

const selectAllCheckboxes = () => {
  const checkboxes = document.querySelectorAll('input[type=checkbox]');
  checkboxes.forEach((cb) => { cb.checked = true; });
}

It's rather simple:

const selectAllCheckboxes = () => {
  const checkboxes = document.querySelectorAll('input[type=checkbox]');
  checkboxes.forEach((cb) => { cb.checked = true; });
}
四叶草在未来唯美盛开 2024-07-17 07:30:04

此示例适用于本机 JavaScript,其中复选框变量名称有所不同,即并非全部为“foo”。

<!DOCTYPE html>
<html>
<body>

<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
    var node_list = document.getElementsByTagName('input');
    var checkboxes = [];
    for (var i = 0; i < node_list.length; i++) 
    {
        var node = node_list[i];
        if (node.getAttribute('type') == 'checkbox') 
        {
            checkboxes.push(node);
        }
    } 
    return checkboxes;
}
function toggle(source) {
    checkboxes = getcheckboxes();
    for (var i = 0 n = checkboxes.length; i < n; i++) 
    {
        checkboxes[i].checked = source.checked;
    }
}
</script>    

<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

</body>
</html>

This sample works with native JavaScript where the checkbox variable name varies, i.e. not all "foo."

<!DOCTYPE html>
<html>
<body>

<p>Toggling checkboxes</p>
<script>
function getcheckboxes() {
    var node_list = document.getElementsByTagName('input');
    var checkboxes = [];
    for (var i = 0; i < node_list.length; i++) 
    {
        var node = node_list[i];
        if (node.getAttribute('type') == 'checkbox') 
        {
            checkboxes.push(node);
        }
    } 
    return checkboxes;
}
function toggle(source) {
    checkboxes = getcheckboxes();
    for (var i = 0 n = checkboxes.length; i < n; i++) 
    {
        checkboxes[i].checked = source.checked;
    }
}
</script>    

<input type="checkbox" name="foo1" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo2" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo3" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo4" value="bar4"> Bar 4<br/>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

</body>
</html>
洒一地阳光 2024-07-17 07:30:04

JavaScript 是你最好的选择。 下面的链接给出了使用按钮取消/全选的示例。 您可以尝试将其调整为使用复选框,只需使用“全选”复选框“onClick 属性即可。

用于选中或取消选中所有复选框的 Javascript 函数

此页面有一个更简单的示例

http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html

JavaScript is your best bet. The link below gives an example using buttons to de/select all. You could try to adapt it to use a check box, just use you 'select all' check box' onClick attribute.

Javascript Function to Check or Uncheck all Checkboxes

This page has a simpler example

http://www.htmlcodetutorial.com/forms/_INPUT_onClick.html

煮茶煮酒煮时光 2024-07-17 07:30:04

如果采用 jQuery 的最佳答案,请记住传递给单击函数的对象是 EventHandler,而不是原始的复选框对象。 因此代码应修改如下。

HTML

<input type="checkbox" name="selectThemAll"/> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

JavaScript

$(function() {
    jQuery("[name=selectThemAll]").click(function(source) { 
        checkboxes = jQuery("[name=foo]");
        for(var i in checkboxes){
            checkboxes[i].checked = source.target.checked;
        }
    });
})

If adopting the top answer for jQuery, remember that the object passed to the click function is an EventHandler, not the original checkbox object. Therefore code should be modified as follows.

HTML

<input type="checkbox" name="selectThemAll"/> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

Javascript

$(function() {
    jQuery("[name=selectThemAll]").click(function(source) { 
        checkboxes = jQuery("[name=foo]");
        for(var i in checkboxes){
            checkboxes[i].checked = source.target.checked;
        }
    });
})
诠释孤独 2024-07-17 07:30:04
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Value="Item 1">Item 1</asp:ListItem>
    <asp:ListItem Value="Item 2">Item 2</asp:ListItem>
    <asp:ListItem Value="Item 3">Item 3</asp:ListItem>
    <asp:ListItem Value="Item 4">Item 4</asp:ListItem>
    <asp:ListItem Value="Item 5">Item 5</asp:ListItem>
    <asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>

<script type="text/javascript">
    function checkAll(obj1) {
        var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');

        for (var i = 0; i < checkboxCollection.length; i++) {
            if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
                checkboxCollection[i].checked = obj1.checked;
            }
        }
    }
</script>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Select All" onclick="checkAll(this);" />
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Value="Item 1">Item 1</asp:ListItem>
    <asp:ListItem Value="Item 2">Item 2</asp:ListItem>
    <asp:ListItem Value="Item 3">Item 3</asp:ListItem>
    <asp:ListItem Value="Item 4">Item 4</asp:ListItem>
    <asp:ListItem Value="Item 5">Item 5</asp:ListItem>
    <asp:ListItem Value="Item 6">Item 6</asp:ListItem>
</asp:CheckBoxList>

<script type="text/javascript">
    function checkAll(obj1) {
        var checkboxCollection = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName('input');

        for (var i = 0; i < checkboxCollection.length; i++) {
            if (checkboxCollection[i].type.toString().toLowerCase() == "checkbox") {
                checkboxCollection[i].checked = obj1.checked;
            }
        }
    }
</script>
云之铃。 2024-07-17 07:30:04

这应该完成工作:

    $(':checkbox').each(function() {
        this.checked = true;                        
    });

that should do the job done:

    $(':checkbox').each(function() {
        this.checked = true;                        
    });
—━☆沉默づ 2024-07-17 07:30:04

由于我无法评论,这里作为答案:
我会用更通用的方式写 Can Berk Güder 的解决方案,
所以您可以将该函数重用于其他复选框

<script type="text/javascript">
  function toggleCheckboxes(source, cbName) {
    checkboxes = document.getElementsByName(cbName);
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = source.checked;
    }
  }
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>

As I cannot comment, here as answer:
I would write Can Berk Güder's solution in a more general way,
so you may reuse the function for other checkboxes

<script type="text/javascript">
  function toggleCheckboxes(source, cbName) {
    checkboxes = document.getElementsByName(cbName);
    for (var i = 0, n = checkboxes.length; i < n; i++) {
      checkboxes[i].checked = source.checked;
    }
  }
</script>
<input type="checkbox" onClick="toggleCheckboxes(this,\'foo\')" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>
<input type="checkbox" name="foo" value="bar5"> Bar 5<br/>
染火枫林 2024-07-17 07:30:04

您可能同一表单上有不同组的复选框。 这是一个通过类名选择/取消选择复选框的解决方案,使用普通的 javascript 函数 document.getElementsByClassName

全选按钮

<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All

一些用于选择的复选框

<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />

javascript

    function selectAll() {
        var blnChecked = document.getElementById("select_all_invoices").checked;
        var check_invoices = document.getElementsByClassName("check_invoice");
        var intLength = check_invoices.length;
        for(var i = 0; i < intLength; i++) {
            var check_invoice = check_invoices[i];
            check_invoice.checked = blnChecked;
        }
    }

You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName

The Select All button

<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All

Some of the checkboxes to select

<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />

The javascript

    function selectAll() {
        var blnChecked = document.getElementById("select_all_invoices").checked;
        var check_invoices = document.getElementsByClassName("check_invoice");
        var intLength = check_invoices.length;
        for(var i = 0; i < intLength; i++) {
            var check_invoice = check_invoices[i];
            check_invoice.checked = blnChecked;
        }
    }
季末如歌 2024-07-17 07:30:04

这就是它的作用,例如,如果您有 5 个复选框,然后单击全部选中,它会选中全部,现在,如果您取消选中所有复选框,可能通过单击每 5 个复选框,那么当您取消选中最后一个复选框时,选择所有复选框也都被取消选中

$("#select-all").change(function(){
   $(".allcheckbox").prop("checked", $(this).prop("checked"))
  })
  $(".allcheckbox").change(function(){
      if($(this).prop("checked") == false){
          $("#select-all").prop("checked", false)
      }
      if($(".allcheckbox:checked").length == $(".allcheckbox").length){
          $("#select-all").prop("checked", true)
      }
  })

This is what this will do, for instance if you have 5 checkboxes, and you click check all,it check all, now if you uncheck all the checkbox probably by clicking each 5 checkboxs, by the time you uncheck the last checkbox, the select all checkbox also gets unchecked

$("#select-all").change(function(){
   $(".allcheckbox").prop("checked", $(this).prop("checked"))
  })
  $(".allcheckbox").change(function(){
      if($(this).prop("checked") == false){
          $("#select-all").prop("checked", false)
      }
      if($(".allcheckbox:checked").length == $(".allcheckbox").length){
          $("#select-all").prop("checked", true)
      }
  })
背叛残局 2024-07-17 07:30:04
$(document).ready(function() {
                $(document).on(' change', 'input[name="check_all"]', function() {
                    $('.cb').prop("checked", this.checked);
                });
            });
$(document).ready(function() {
                $(document).on(' change', 'input[name="check_all"]', function() {
                    $('.cb').prop("checked", this.checked);
                });
            });
笛声青案梦长安 2024-07-17 07:30:04

使用 jQuery 和淘汰赛:

通过此绑定主复选框与底层复选框保持同步,除非所有复选框均已选中,否则它将被取消选中。

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();
  }
};

在 HTML 中:

<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>

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:

<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>
箜明 2024-07-17 07:30:04

使用 jQuery 制作简写版本

全选复选框

<input type="checkbox" id="chkSelectAll">

子复选框

<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">

jQuery

$("#chkSelectAll").on('click', function(){
     this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);  
})

to make it in short-hand version by using jQuery

The select all checkbox

<input type="checkbox" id="chkSelectAll">

The children checkbox

<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">
<input type="checkbox" class="chkDel">

jQuery

$("#chkSelectAll").on('click', function(){
     this.checked ? $(".chkDel").prop("checked",true) : $(".chkDel").prop("checked",false);  
})
一人独醉 2024-07-17 07:30:04

下面的方法非常容易理解,您可以在几分钟内实现现有的表单

使用 Jquery,

$(document).ready(function() {
  $('#check-all').click(function(){
    $("input:checkbox").attr('checked', true);
  });
  $('#uncheck-all').click(function(){
    $("input:checkbox").attr('checked', false);
  });
});

以 HTML 形式放在按钮下方

<a id="check-all" href="javascript:void(0);">check all</a>
<a id="uncheck-all" href="javascript:void(0);">uncheck all</a> 

仅使用 JavaScript,

<script type="text/javascript">
function checkAll(formname, checktoggle)
{
  var checkboxes = new Array(); 
  checkboxes = document[formname].getElementsByTagName('input');

  for (var i=0; i<checkboxes.length; i++)  {
    if (checkboxes[i].type == 'checkbox')   {
      checkboxes[i].checked = checktoggle;
    }
  }
}
</script>

以 HTML 形式放在按钮下方

<button onclick="javascript:checkAll('form3', true);" href="javascript:void();">check all</button>

<button onclick="javascript:checkAll('form3', false);" href="javascript:void();">uncheck all</button>

Below methods are very Easy to understand and you can implement existing forms in minutes

With Jquery,

$(document).ready(function() {
  $('#check-all').click(function(){
    $("input:checkbox").attr('checked', true);
  });
  $('#uncheck-all').click(function(){
    $("input:checkbox").attr('checked', false);
  });
});

in HTML form put below buttons

<a id="check-all" href="javascript:void(0);">check all</a>
<a id="uncheck-all" href="javascript:void(0);">uncheck all</a> 

With just using javascript,

<script type="text/javascript">
function checkAll(formname, checktoggle)
{
  var checkboxes = new Array(); 
  checkboxes = document[formname].getElementsByTagName('input');

  for (var i=0; i<checkboxes.length; i++)  {
    if (checkboxes[i].type == 'checkbox')   {
      checkboxes[i].checked = checktoggle;
    }
  }
}
</script>

in HTML form put below buttons

<button onclick="javascript:checkAll('form3', true);" href="javascript:void();">check all</button>

<button onclick="javascript:checkAll('form3', false);" href="javascript:void();">uncheck all</button>

不…忘初心 2024-07-17 07:30:04

您可以使用此代码。

var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
  let checkboxes = document.querySelectorAll(".dlMultiDelete");
  checkboxes.forEach(function (ele) {
    ele.checked = !!checkbox.checked;
  });
});

You can Use This code.

var checkbox = document.getElementById("dlCheckAll4Delete");
checkbox.addEventListener("click", function (event) {
  let checkboxes = document.querySelectorAll(".dlMultiDelete");
  checkboxes.forEach(function (ele) {
    ele.checked = !!checkbox.checked;
  });
});
是伱的 2024-07-17 07:30:04

这是backbone.js 的实现:

events: {
    "click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {

    var checkboxes = document.getElementsByName('options');
    for(var i=0; i<checkboxes.length; i++) {
        checkboxes[i].checked = event.currentTarget.checked;
    }

},

Here is a backbone.js implementation:

events: {
    "click #toggleChecked" : "toggleChecked"
},
toggleChecked: function(event) {

    var checkboxes = document.getElementsByName('options');
    for(var i=0; i<checkboxes.length; i++) {
        checkboxes[i].checked = event.currentTarget.checked;
    }

},
半透明的墙 2024-07-17 07:30:04

html

<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3

javascript

$(':checkbox.all').change(function(){
  $(':checkbox.item').prop('checked', this.checked);
});

html

<input class='all' type='checkbox'> All
<input class='item' type='checkbox' value='1'> 1
<input class='item' type='checkbox' value='2'> 2
<input class='item' type='checkbox' value='3'> 3

javascript

$(':checkbox.all').change(function(){
  $(':checkbox.item').prop('checked', this.checked);
});
烟柳画桥 2024-07-17 07:30:04

1:添加onchange事件处理程序

<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>

2:修改代码以处理选中/未选中

 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
 }

1: Add the onchange event Handler

<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>

2: Modify the code to handle checked/unchecked

 function checkAll(ele) {
     var checkboxes = document.getElementsByTagName('input');
     if (ele.checked) {
         for (var i = 0; i < checkboxes.length; i++) {
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = true;
             }
         }
     } else {
         for (var i = 0; i < checkboxes.length; i++) {
             console.log(i)
             if (checkboxes[i].type == 'checkbox') {
                 checkboxes[i].checked = false;
             }
         }
     }
 }
淡水深流 2024-07-17 07:30:04

您可以使用这个简单的代码

$('.checkall').click(function(){
    var checked = $(this).prop('checked');
    $('.checkme').prop('checked', checked);
});

You can use this simple code

$('.checkall').click(function(){
    var checked = $(this).prop('checked');
    $('.checkme').prop('checked', checked);
});
笑饮青盏花 2024-07-17 07:30:04

也许有点晚了,但是在处理全选复选框时,我相信您还应该处理选中全选复选框,然后取消选中下面的复选框之一的情况。

在这种情况下,它应该自动取消选中全部选中复选框。

此外,当手动检查所有复选框时,您最终应该自动检查“检查所有”复选框。

您需要两个事件处理程序,一个用于选中所有框,另一个用于单击下面的任何单个框时。

// HANDLES THE INDIVIDUAL CHECKBOX CLICKS
function client_onclick() {
    var selectAllChecked = $("#chk-clients-all").prop("checked");

    // IF CHECK ALL IS CHECKED, AND YOU'RE UNCHECKING AN INDIVIDUAL BOX, JUST UNCHECK THE CHECK ALL CHECKBOX.
    if (selectAllChecked && $(this).prop("checked") == false) {
        $("#chk-clients-all").prop("checked", false);
    } else { // OTHERWISE WE NEED TO LOOP THROUGH INDIVIDUAL CHECKBOXES AND SEE IF THEY ARE ALL CHECKED, THEN CHECK THE SELECT ALL CHECKBOX ACCORDINGLY.
        var allChecked = true;
        $(".client").each(function () {
            allChecked = $(this).prop("checked");
            if (!allChecked) {
                return false;
            }
        });
        $("#chk-clients-all").prop("checked", allChecked);
    }
}

// HANDLES THE TOP CHECK ALL CHECKBOX
function client_all_onclick() {
    $(".client").prop("checked", $(this).prop("checked"));
}

Maybe a bit late, but when dealing with a check all checkbox, I believe you should also handle the scenario for when you have the check all checkbox checked, and then unchecking one of the checkboxes below.

In that case it should automatically uncheck the check all checkbox.

Also when manually checking all the checkboxes, you should end up with the check all checkbox being automatically checked.

You need two event handlers, one for the check all box, and one for when clicking any of the single boxes below.

// HANDLES THE INDIVIDUAL CHECKBOX CLICKS
function client_onclick() {
    var selectAllChecked = $("#chk-clients-all").prop("checked");

    // IF CHECK ALL IS CHECKED, AND YOU'RE UNCHECKING AN INDIVIDUAL BOX, JUST UNCHECK THE CHECK ALL CHECKBOX.
    if (selectAllChecked && $(this).prop("checked") == false) {
        $("#chk-clients-all").prop("checked", false);
    } else { // OTHERWISE WE NEED TO LOOP THROUGH INDIVIDUAL CHECKBOXES AND SEE IF THEY ARE ALL CHECKED, THEN CHECK THE SELECT ALL CHECKBOX ACCORDINGLY.
        var allChecked = true;
        $(".client").each(function () {
            allChecked = $(this).prop("checked");
            if (!allChecked) {
                return false;
            }
        });
        $("#chk-clients-all").prop("checked", allChecked);
    }
}

// HANDLES THE TOP CHECK ALL CHECKBOX
function client_all_onclick() {
    $(".client").prop("checked", $(this).prop("checked"));
}
迷鸟归林 2024-07-17 07:30:03
<script language="JavaScript">
function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var checkbox in checkboxes)
    checkbox.checked = source.checked;
}
</script>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

更新:

foreach...in 构造似乎不起作用,至少在本例中,在 Safari 5 或 Chrome 5 中。此代码应该适用于所有浏览器:

function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}
<script language="JavaScript">
function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var checkbox in checkboxes)
    checkbox.checked = source.checked;
}
</script>

<input type="checkbox" onClick="toggle(this)" /> Toggle All<br/>

<input type="checkbox" name="foo" value="bar1"> Bar 1<br/>
<input type="checkbox" name="foo" value="bar2"> Bar 2<br/>
<input type="checkbox" name="foo" value="bar3"> Bar 3<br/>
<input type="checkbox" name="foo" value="bar4"> Bar 4<br/>

UPDATE:

The for each...in construct doesn't seem to work, at least in this case, in Safari 5 or Chrome 5. This code should work in all browsers:

function toggle(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;
  }
}
第七度阳光i 2024-07-17 07:30:03

使用 jQuery

// Listen for click on toggle checkbox
$('#select-all').click(function(event) {   
    if(this.checked) {
        // Iterate each checkbox
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;                       
        });
    }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />

<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />

Using jQuery:

// Listen for click on toggle checkbox
$('#select-all').click(function(event) {   
    if(this.checked) {
        // Iterate each checkbox
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;                       
        });
    }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />

<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />

万人眼中万个我 2024-07-17 07:30:03

我不确定是否有人以这种方式回答(使用 jQuery):

  $( '#container .toggle-button' ).click( function () {
    $( '#container input[type="checkbox"]' ).prop('checked', this.checked)
  })

它很干净,没有循环或 if /else 子句并起到魅力作用。

I'm not sure anyone hasn't answered in this way (using jQuery):

  $( '#container .toggle-button' ).click( function () {
    $( '#container input[type="checkbox"]' ).prop('checked', this.checked)
  })

It's clean, has no loops or if/else clauses and works as a charm.

花想c 2024-07-17 07:30:03

我很惊讶没有人提到document.querySelectorAll()< /a>. 纯 JavaScript 解决方案,适用于 IE9+。

function toggle(source) {
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i] != source)
            checkboxes[i].checked = source.checked;
    }
}
<input type="checkbox" onclick="toggle(this);" />Check all?<br />

<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />

I'm surprised no one mentioned document.querySelectorAll(). Pure JavaScript solution, works in IE9+.

function toggle(source) {
    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i] != source)
            checkboxes[i].checked = source.checked;
    }
}
<input type="checkbox" onclick="toggle(this);" />Check all?<br />

<input type="checkbox" />Bar 1<br />
<input type="checkbox" />Bar 2<br />
<input type="checkbox" />Bar 3<br />
<input type="checkbox" />Bar 4<br />

メ斷腸人バ 2024-07-17 07:30:03

这是一种不同的方式,更少的代码

$(function () {
       $('#select-all').click(function (event) {
          
           var selected = this.checked;
           // Iterate each checkbox
           $(':checkbox').each(function () {    this.checked = selected; });

       });
    });

here's a different way less code

$(function () {
       $('#select-all').click(function (event) {
          
           var selected = this.checked;
           // Iterate each checkbox
           $(':checkbox').each(function () {    this.checked = selected; });

       });
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文