How to get all checked checkboxes

前端 未结 4 649
离开以前
离开以前 2020-11-27 03:30

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 ho

相关标签:
4条回答
  • 2020-11-27 03:47

    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");
    
    0 讨论(0)
  • 2020-11-27 03:54

    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>

    0 讨论(0)
  • 2020-11-27 04:02

    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.

    0 讨论(0)
  • 2020-11-27 04:11

    In IE9+, Chrome or Firefox you can do:

    var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');
    
    0 讨论(0)
提交回复
热议问题