Html 当一个复选框被选中时,选中所有其他复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19658068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:51:25  来源:igfitidea点击:

Check all other checkboxes when one is checked

javascripthtmljsp

提问by Smajl

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):

我有一个表单和一组复选框。(这些复选框是动态创建的,但我认为这对这个问题并不重要)。生成它们的代码如下所示(表单的一部分):

<div id="ScrollCB">
    <input type="checkbox" name="ALL" value="checked" checked="checked">
    All (if nothing selected, this is default) <br>
    <c:forEach items="${serviceList}" var="service">
       <input type="checkbox" name="${service}" value="checked"> ${service} <br>
    </c:forEach>
</div>

What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).

我想要做的是控制是否选中标记为“ALL”的复选框,如果选中,则选中所有其他复选框(如果未选中,则取消选中所有复选框)。

I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):

我尝试用这样的 javascript 来做这个(找到了一些教程),但它不起作用(我是 javascript 的真正新手,难怪):

<script type="text/javascript">
  $ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
  $(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>

Could you tell me some simple approach how to get it work? Thanks a lot!

你能告诉我一些如何让它工作的简单方法吗?非常感谢!

回答by

demo

演示

updated_demo

更新演示

HTML:

HTML:

<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>

<div id="checkboxlist">

    <label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox4</label><br />

</div>

JS:

JS:

$('.selectall').click(function() {
    if ($(this).is(':checked')) {
        $('div input').attr('checked', true);
    } else {
        $('div input').attr('checked', false);
    }
});

回答by monkey

HTML:

HTML:

<form>
<label>
    <input type="checkbox" id="selectall"/> Select all
</label>
<div id="checkboxlist">
    <label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
</form>

JS:

JS:

$('#selectall').click(function() {
    $(this.form.elements).filter(':checkbox').prop('checked', this.checked);
});

http://jsfiddle.net/wDnAd/1/

http://jsfiddle.net/wDnAd/1/

回答by Fandango68

Thanks to @Ashish, I have expanded it slightly to allow the "master" checkbox to be automaticallychecked or unchecked, if you manually tick all the sub checkboxes.

感谢@Ashish,如果您手动勾选所有子复选框,我已经稍微扩展了它以允许自动选中或取消选中“主”复选框。

FIDDLE

小提琴

HTML

HTML

<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>

<div id="checkboxlist">
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
    <label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>

SCRIPT

脚本

$('.selectall').click(function() {
    if ($(this).is(':checked')) {
        $('input:checkbox').prop('checked', true);
    } else {
        $('input:checkbox').prop('checked', false);
    }
});

And now add this to manage the master checkbox as well...

现在添加它来管理主复选框......

$("input[type='checkbox'].justone").change(function(){
    var a = $("input[type='checkbox'].justone");
    if(a.length == a.filter(":checked").length){
        $('.selectall').prop('checked', true);
    }
    else {
        $('.selectall').prop('checked', false);
    }
});

回答by Shankar Prakash G

Add extra script according to your checkbox group:

根据您的复选框组添加额外的脚本:

<script language="JavaScript">
function selectAll(source) {
    checkboxes = document.getElementsByName('colors[]');
    for(var i in checkboxes)
        checkboxes[i].checked = source.checked;
}
</script>

HTML Code:

HTML代码:

<input type="checkbox" id="selectall" onClick="selectAll(this,'color')" />Select All
<ul>
<li><input type="checkbox" name="colors[]" value="red" />Red</li>
<li><input type="checkbox" name="colors[]" value="blue" />Blue</li>
<li><input type="checkbox" name="colors[]" value="green" />Green</li>
<li><input type="checkbox" name="colors[]" value="black" />Black</li>
</ul>

回答by Amgad Mohamed

use this i hope to help you i know that this is a late answer but if any one come here again

用这个我希望能帮助你我知道这是一个迟到的答案但是如果有人再次来到这里

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

回答by jazZRo

You can use the :first selector to find the first input and bind the change event to it. In my example below I use the :checked state of the first input to define the state of it's siblings. I would also suggest to put the code in the JQuery ready event.

您可以使用 :first 选择器来查找第一个输入并将更改事件绑定到它。在下面的示例中,我使用第一个输入的 :checked 状态来定义它的兄弟姐妹的状态。我还建议将代码放在 JQuery 就绪事件中。

    $('document').ready(function(){   
        $('#ScrollCB input:first').bind('change', function() {
            var first = $(this);
            first.siblings().attr('checked', first.is(':checked'));
        });
    });

回答by usernolongerregistered

You can use jQuery like so:

你可以像这样使用jQuery:

jQuery

jQuery

$('[name="ALL"]:checkbox').change(function () {
   if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
   else $('input:checkbox').removeAttr('checked');
});

A fiddle.

一把小提琴

回答by epascarello

I am not sure why you would use a label when you have a name on the checkbox. Use that as the selector. Plus your code has no labels in the HTML markup so it will not find anything.

当复选框上有名称时,我不确定为什么要使用标签。将其用作选择器。此外,您的代码在 HTML 标记中没有标签,因此不会找到任何内容。

Here is the basic idea

这是基本思想

$(document).on("click",'[name="ALL"]',function() {
    $(this).siblings().prop("checked",this.checked);
});

if there are other elements that are siblings, than you would beed to filter the siblings

如果还有其他元素是同级元素,那么您应该过滤同级元素

$(document).on("click",'[name="ALL"]',function() {
    $(this).siblings(":checkbox").prop("checked",this.checked);
});

jsFiddle

js小提琴

回答by Arjun

var selectedIds = [];
function toggle(source) {
    checkboxes = document.getElementsByName('ALL');
    for ( var i in checkboxes)
        checkboxes[i].checked = source.checked;
}
function addSelects() {

    var ids = document.getElementsByName('ALL');

    for ( var i = 0; i < ids.length; i++) {
        if (ids[i].checked == true) {
            selectedIds.push(ids[i].value);
        }
    }
}

In HTML:

在 HTML 中:

Master Check box <input type="checkbox" onClick="toggle(this);">

主复选框 <input type="checkbox" onClick="toggle(this);">

Other Check boxes <input type="checkbox" name="ALL">

其他复选框 <input type="checkbox" name="ALL">

回答by Tarun Kumar

Only in JavaScript with auto check/uncheck functionality of master when any child is checked/unchecked.

仅在选中/取消选中任何子项时,仅在JavaScript中使用Auto Check / Uncheck功能。

function FnCheckAll()
    {
        var ChildChkBoxes = document.getElementsByName("ChildCheckBox");
        for (i = 0; i < ChildChkBoxes.length; i++)
        {
            ChildChkBoxes[i].checked = document.forms[0].CheckAll.checked;
        }
    }
function FnCheckChild()
    {
        if (document.forms[0].ChildCheckBox.length > document.querySelectorAll('input[name="ChildCheckBox"]:checked').length)
            document.forms[0].CheckAll.checked = false;
        else
            document.forms[0].CheckAll.checked = true;
    }

Master CheckBox:

主复选框:

<input type="checkbox" name="CheckAll" id="CheckAll" onchange="FnCheckAll()" />

Child CheckBox:

子复选框:

<input type="checkbox" name="ChildCheckBox" id="ChildCheckBox" onchange="FnCheckChild()" value="@employee.Id" />```