如何获取所有已选中的复选框。

81

我有一组名称相同的输入复选框,我想使用JavaScript确定哪些复选框已经被选中,该怎么做? 我只知道如下获取所有复选框的方法:

var checkboxes = document.getElementsByName('mycheckboxes');

1
是的,已经有了,但它们都是使用JQuery解决方案,而我需要一个纯JS的解决方案,这就是区别所在。 - Sameh Farahat
请看以下内容:https://dev59.com/hEnSa4cB1Zd3GeqPQbmV - LCJ
7个回答

168

在IE9+,Chrome或Firefox中,您可以执行:

var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

108

一个简单的for循环,它测试checked属性并将选中的复选框附加到另一个数组中。从那里,如果需要,您可以进一步处理checkboxesChecked数组。

// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
  var checkboxes = document.getElementsByName(chkboxName);
  var checkboxesChecked = [];
  // loop over them all
  for (var i=0; i<checkboxes.length; i++) {
     // And stick the checked ones onto an array...
     if (checkboxes[i].checked) {
        checkboxesChecked.push(checkboxes[i]);
     }
  }
  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}

// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");

1
我支持这个解决方案。+1 给我。这是纯 JavaScript,而且它很有效。 - Federico Zancan
你需要返回“checkboxesChecked”吗? - jward01
@jward01 如果数组长度为非零或 null,则会有条件地执行该操作。凭借更多的经验和远见,现在我可能会返回空数组而不是 null。 - Michael Berkowski
@Elyor 循环或映射返回的 checkBoxes,以返回值属性 var allString = checkedBoxes.map(function(i) {return i.value;}).join(' '); 或类似内容。 - Michael Berkowski
最终我找到了这个问题的简单解决方案。 - user5228393
显示剩余4条评论

11

一行代码获取所有选中复选框的值并存入数组

const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);
console.log(data);
<div class="row">
    <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> 
    <label class="custom-control-label" for="inlineCheckbox1">Option1</label>
    <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> 
    <label class="custom-control-label" for="inlineCheckbox1">Option2</label>
    <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> 
    <label class="custom-control-label" for="inlineCheckbox1">Option3</label>
</div>


11
对于一个简单的两行(或一行)代码,可以写成以下形式:
checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);

这里的Array.prototype.slice.call()将所有名称为“NameOfCheckboxes”的复选框对象NodeList转换为一个新数组,然后使用filter方法进行过滤。例如,您还可以通过在第二行末尾添加.map(ch => ch.value)来提取复选框的值。

=>是JavaScript的箭头函数符号。


太棒了!谢谢你! - nickpapoutsis

4
您可以为表单中的所有复选框提供一个类,然后像这样获取它们的选中属性:

document.querySelectorAll('.mycheckbox').forEach(function(elem) {
        console.log(elem.checked);
});
<div>
<label><input type="checkbox" name="mycheckbox[]" class="mycheckbox" value="1" checked="checked">Johnson</label>
</div>

<div>
<label><input type="checkbox" name="mycheckbox[]" class="mycheckbox" value="2">
Henry</label>
</div>

<div>
<label><input type="checkbox" name="mycheckbox[]" class="mycheckbox" value="3" checked="checked">
Donald</label>
</div>


2
如果您正在使用<form>元素,您可以利用以下方式使用表单事件:

function onSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);
    console.log(data.getAll("mycheckboxs")) // will print only checked inputs
}
<form onsubmit="onSubmit(event)">
   <label for="checkbox1">
   Checkbox 1
   <input id="checkbox1" name="mycheckboxs" type="checkbox"  checked="true" value="1"/>
   </label><br/>
   <label for="checkbox2">
   Checkbox 2
   <input id="checkbox2" name="mycheckboxs" type="checkbox"  value="2"/>
   </label><br/>
   <label for="checkbox3">
   Checkbox 3
   <input id="checkbox3" name="mycheckboxs" type="checkbox" value="3"/>
   </label><br/>
   <label for="checkbox4">
   Checkbox 4
   <input id="checkbox4" name="mycheckboxs" type="checkbox"  checked="true" value="4"/>
   </label><br/>
   <div>
      <br/> 
      <button type="submit">Submit</button>
   </div>
</form>

祝你好运!


0

$(document).ready(function () {
            // Single check Box Checked 
            $(document).on("change", ".check_class", function () {
                $(".check_class").prop("checked", false);
                $(this).prop("checked", true);
                var value = $(this).val();
                console.log("Device Serial No is = " + value)
            });

            //get all  emp Selected 
            $(document).on("click", "#EmpUpload", function (evnt) {
                var emp =[]
                const data = [...document.querySelectorAll('.EmpID:checked')].map(e => e.value);
                emp.push(data)
                console.log("Selected Emp Here [] = " + emp);
            });
        });
<!DOCTYPE html>
<html>

<head>
    <title>Employee CheckBox Data Sample </title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
        integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
</head>

<body>
    <div class="container-fluid w-75 pt-5"> 
           
        <div class="row border-top">  
          <div class="col-md-12">
            <button type="button" class="btn btn-success float-right" id="EmpUpload">Get On Click</button>
        </div>
            <div class="col-md-4 border-right">
                <table id="example" class="display w-100">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Device</th>
                            <th>Location</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="check_class" value="990099" name="serialNo" /></td>
                            <td>Office</td>
                            <td>Delhi</td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="check_class" value="778899" name="serialNo" /></td>
                            <td>Garrett</td>
                            <td>Accountant</td>
                        </tr>
                     </tfoot>
                </table>
            </div>

            <div class="col-md-8">               
                <table id="example" class="display" style="width:100%">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="EmpID" value="1001" name="serialNo" /></td>
                            <td>1001</td>
                            <td>Shaqubi Hassan</td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="EmpID" value="1002" name="serialNo" /></td>
                            <td>1002</td>
                            <td>Balwinder Singh</td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="EmpID" value="1003" name="serialNo" /></td>
                            <td>1003</td>
                            <td>Balwinder Singh</td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="EmpID" value="1004" name="serialNo" /></td>
                            <td>1004</td>
                            <td>Singh</td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="EmpID" value="1005" name="serialNo" /></td>
                            <td>1005</td>
                            <td>Sohi</td>
                        </tr>
                        </tfoot>
                </table>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   
</body>

</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接