admin管理员组

文章数量:1134605

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

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

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

var checkboxes = document.getElementsByName('mycheckboxes');
Share Improve this question edited Sep 27, 2018 at 5:39 Minhaj Patel 5791 gold badge7 silver badges21 bronze badges asked Dec 19, 2011 at 15:06 Sameh FarahatSameh Farahat 1,8038 gold badges23 silver badges26 bronze badges 2
  • 1 yes there are already but all of them, the solution is with JQuery, and i need a plain JS solution, that's the difference. – Sameh Farahat Commented Dec 19, 2011 at 15:27
  • Take a look at following too stackoverflow.com/questions/1543017/… – LCJ Commented May 22, 2014 at 19:24
Add a comment  | 

7 Answers 7

Reset to default 176

In IE9+, Chrome or Firefox you can do:

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

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.

// 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");

Get all the checked checkbox value in an array - one liner

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>

For a simple two- (or one) liner this code can be:

checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);

Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2. The => is javascript's arrow function notation.

You can just give a class for all checkboxes in the form, and get their checked property like this:

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>

if you are using the <form> element you can take advantage of the form event using :

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>

Good luck!!

$(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/[email protected]/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>

本文标签: javascriptHow to get all checked checkboxesStack Overflow