如何获得所有选中的复选框

时间:2021-10-20 09:48:10

I have a set of input checkboxes with same name and I would like determine which checkboxes have been checked using javascript, how can I achieve that? I know only how to get all the checkboxes as follows:

我有一组名称相同的输入复选框,我想确定使用javascript检查了哪些复选框,如何实现呢?我只知道如何得到以下所有的复选框:

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

2 个解决方案

#1


73  

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.

一个简单的for循环,它测试已检查的属性并将已检查的属性附加到一个单独的数组中。从那里,如果需要,您可以进一步处理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");

#2


50  

In IE9+, Chrome or Firefox you can do:

在IE9+、Chrome或Firefox中,你可以做到:

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

#1


73  

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.

一个简单的for循环,它测试已检查的属性并将已检查的属性附加到一个单独的数组中。从那里,如果需要,您可以进一步处理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");

#2


50  

In IE9+, Chrome or Firefox you can do:

在IE9+、Chrome或Firefox中,你可以做到:

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