【问题标题】:Getting all selected checkboxes in an array获取数组中所有选中的复选框
【发布时间】:2010-10-10 01:18:20
【问题描述】:

所以我有这些复选框:

<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />

等等。其中大约有 6 个,并且是手动编码的(即不是从数据库中获取的),因此它们可能会在一段时间内保持不变。

我的问题是如何将它们全部放在一个数组中(在 javascript 中),这样我就可以在使用 Jquery 发出 AJAX $.post 请求时使用它们。

有什么想法吗?

编辑:我只想将选中的复选框添加到数组中

【问题讨论】:

  • 虽然other question 较新且这个更受欢迎,但另一个有更好、更简洁的答案集合(包括这里的策略,还有一些)。
  • 这个问题没有尝试过的代码,但仍然吸引了赞成票和答案,投票结束

标签: javascript jquery ajax dhtml


【解决方案1】:

格式化:

$("input:checkbox[name=type]:checked").each(function(){
    yourArray.push($(this).val());
});

希望它会起作用。

【讨论】:

  • 如果取消选中复选框,如何从数组中删除值
  • @JubinPatel 您只需要在此代码之前重置数组。 yourArray = []
  • 你也可以立即使用map而不是each来定义你的数组:var yourArray = $("input:checkbox[name=type]:checked").map(function(){return $(this).val()}).get()
  • function get_selected_checkboxes_array(){ var ch_list=Array(); $("input:checkbox[type=checkbox]:checked").each(function(){ch_list.push($(this).val());}); return ch_list; }
【解决方案2】:

纯 JS

对于那些不想使用 jQuery 的人

var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')

for (var i = 0; i < checkboxes.length; i++) {
  array.push(checkboxes[i].value)
}

【讨论】:

  • 总是喜欢香草的 JS 答案。
  • 是的,有些时候我们真的不想使用 jQuery
  • 也是您的解决方案,带有适用于 vanilla JS 的地图功能。 Array.from(document.querySelectorAll("input[name='type']:checked")).map((elem) =&gt; elem.value)
【解决方案3】:
var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 

【讨论】:

  • 据我了解上面的代码,它遍历所有复选框并取消选中它们。这个答案与问题有何联系?
  • 这只是遍历复选框并取消选中它们。正确答案在VanillaJS中,请看下面zahid ullah的答案。
  • 这如何回答这个问题?这做了一些与所要求的完全无关的事情。为什么会有这么多赞?我错过了什么,还是在人们投票后对问题进行了编辑?
【解决方案4】:

我没有测试它,但它应该可以工作

<script type="text/javascript">
var selected = new Array();

$(document).ready(function() {

  $("input:checkbox[name=type]:checked").each(function() {
       selected.push($(this).val());
  });

});

</script>

【讨论】:

  • 推动在数组中添加值但取消选中要删除什么?
【解决方案5】:

ES6 版本:

const values = Array
  .from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);

function getCheckedValues() {
  return Array.from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);
}

const resultEl = document.getElementById('result');

document.getElementById('showResult').addEventListener('click', () => {
  resultEl.innerHTML = getCheckedValues();
});
<input type="checkbox" name="type" value="1" />1
<input type="checkbox" name="type" value="2" />2
<input type="checkbox" name="type" value="3" />3
<input type="checkbox" name="type" value="4" />4
<input type="checkbox" name="type" value="5" />5

<br><br>
<button id="showResult">Show checked values</button>
<br><br>
<div id="result"></div>

【讨论】:

    【解决方案6】:

    这应该可以解决问题:

    $('input:checked');
    

    我认为您没有其他可以检查的元素,但如果您这样做,您必须使其更具体:

    $('input:checkbox:checked');
    
    $('input:checkbox').filter(':checked');
    

    【讨论】:

      【解决方案7】:

      纯 JavaScript,无需临时变量:

      Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
      

      【讨论】:

      • 使用 vanilla JS 的最简洁的解决方案
      • 其实应该是...map((i,e) =&gt; e.value))...
      • @spetsnaz 索引是第二个元素,所以如果你需要索引,你需要做 (e,i)。在这种情况下,这当然不是必需的。见developer.mozilla.org/nl/docs/Web/JavaScript/Reference/…
      • 不错的单行解决方案。可以很容易地在以输入名称作为参数和返回语句来获取数组的方法中重用。
      【解决方案8】:

      在 MooTools 1.3 中(撰写本文时最新):

      var array = [];
      $$("input[type=checkbox]:checked").each(function(i){
          array.push( i.value );
      });
      

      【讨论】:

      • 没有意识到问题的年代或解决方案的性质是相关的。
      • 因为我在使用 MooTools 寻找相同问题的答案时发现了这个问题。
      • 请注意,此答案与 MooTools 1.3 相关,而不是 jQuery。
      【解决方案9】:

      如果你想使用 vanilla JS,你可以像 @zahid-ullah 那样做,但要避免循环:

        var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
          return c.checked;
        }).map(function(c) {
          return c.value;
        });
      

      相同的代码在 ES6 中看起来更好:

      var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);
      

      window.serialize = function serialize() {
        var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
          return c.checked;
        }).map(function(c) {
          return c.value;
        });
        document.getElementById('serialized').innerText = JSON.stringify(values);
      }
      label {
        display: block;
      }
      <label>
        <input type="checkbox" name="fruits[]" value="banana">Banana
      </label>
      <label>
        <input type="checkbox" name="fruits[]" value="apple">Apple
      </label>
      <label>
        <input type="checkbox" name="fruits[]" value="peach">Peach
      </label>
      <label>
        <input type="checkbox" name="fruits[]" value="orange">Orange
      </label>
      <label>
        <input type="checkbox" name="fruits[]" value="strawberry">Strawberry
      </label>
      <button onclick="serialize()">Serialize
      </button>
      <div id="serialized">
      </div>

      【讨论】:

        【解决方案10】:

        在 Javascript 中会是这样的 (Demo Link):

        // get selected checkboxes
        function getSelectedChbox(frm) {
          var selchbox = [];// array that will store the value of selected checkboxes
          // gets all the input tags in frm, and their number
          var inpfields = frm.getElementsByTagName('input');
          var nr_inpfields = inpfields.length;
          // traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
          for(var i=0; i<nr_inpfields; i++) {
            if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
          }
          return selchbox;
        }   
        

        【讨论】:

          【解决方案11】:
          var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
                  return this.value;
              }).get();
          

          【讨论】:

            【解决方案12】:

            选中时添加复选框的值,取消选中时减去值

            $('#myDiv').change(function() {
              var values = 0.00;
              {
                $('#myDiv :checked').each(function() {
                  //if(values.indexOf($(this).val()) === -1){
                  values=values+parseFloat(($(this).val()));
                  // }
                });
                console.log( parseFloat(values));
              }
            });
            <div id="myDiv">
              <input type="checkbox" name="type" value="4.00" />
              <input type="checkbox" name="type" value="3.75" />
              <input type="checkbox" name="type" value="1.25" />
              <input type="checkbox" name="type" value="5.50" />
            </div>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

            【讨论】:

            • 请在您的答案中添加一些解释。纯代码答案通常没有用。
            【解决方案13】:

            在现代浏览器中使用 vanilla JS 执行此操作的另一种方法(不支持 IE,遗憾的是在撰写本文时不支持 iOS Safari)是 FormData.getAll()

            var formdata   = new FormData(document.getElementById("myform"));
            var allchecked = formdata.getAll("type"); // "type" is the input name in the question
            
            // allchecked is ["1","3","4","5"]  -- if indeed all are checked
            

            【讨论】:

              【解决方案14】:

              使用这个:

              var arr = $('input:checkbox:checked').map(function () {
                return this.value;
              }).get();
              

              【讨论】:

                【解决方案15】:

                按输入名称选择复选框

                var category_id = [];
                
                $.each($("input[name='yourClass[]']:checked"), function(){                    
                    category_id.push($(this).val());
                });
                

                【讨论】:

                  【解决方案16】:

                  使用 Jquery

                  你只需要为每个输入添加类,我已经添加类“源”你当然可以改变它

                  <input class="source" type="checkbox" name="type" value="4" />
                  <input class="source" type="checkbox" name="type" value="3" />
                  <input class="source" type="checkbox" name="type" value="1" />
                  <input class="source" type="checkbox" name="type" value="5" />
                  
                  <script type="text/javascript">
                  $(document).ready(function() {
                      var selected_value = []; // initialize empty array 
                      $(".source:checked").each(function(){
                          selected_value.push($(this).val());
                      });
                      console.log(selected_value); //Press F12 to see all selected values
                  });
                  </script>
                  

                  【讨论】:

                    【解决方案17】:

                    function selectedValues(ele){
                      var arr = [];
                      for(var i = 0; i < ele.length; i++){
                        if(ele[i].type == 'checkbox' && ele[i].checked){
                          arr.push(ele[i].value);
                        }
                      }
                      return arr;
                    }

                    【讨论】:

                    • 为了得到一个有用的答案,这个反应需要扩展。解释为什么这是问题的答案。
                    • 欢迎来到 Stack Overflow 并感谢您的贡献!如果您能阅读本指南How to write a good answer 并相应地调整您的答案,那就太好了。谢谢!
                    【解决方案18】:
                    var array = []
                        $("input:checkbox[name=type]:checked").each(function(){
                            array.push($(this).val());
                        });
                    

                    【讨论】:

                      【解决方案19】:

                      如果您使用按钮单击或其他方式运行插入,请使用注释的 if 块来防止添加已经在数组中的值

                      $('#myDiv').change(function() {
                        var values = [];
                        {
                          $('#myDiv :checked').each(function() {
                            //if(values.indexOf($(this).val()) === -1){
                            values.push($(this).val());
                            // }
                          });
                          console.log(values);
                        }
                      });
                      <div id="myDiv">
                        <input type="checkbox" name="type" value="4" />
                        <input type="checkbox" name="type" value="3" />
                        <input type="checkbox" name="type" value="1" />
                        <input type="checkbox" name="type" value="5" />
                      </div>
                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

                      【讨论】:

                        【解决方案20】:

                        你可以试试这样的:

                        $('input[type="checkbox"]').change(function(){
                               var checkedValue = $('input:checkbox:checked').map(function(){
                                        return this.value;
                                    }).get();         
                                    alert(checkedValue);   //display selected checkbox value     
                         })
                        

                        这里

                        $('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
                        $('input:checkbox:checked').map(function()  looping on all checkbox,
                        

                        【讨论】:

                          【解决方案21】:

                          这是我解决同样问题的代码,有人也可以试试这个。 jquery

                          <script>
                          $(document).ready(function(){`
                          $(".check11").change(function(){
                          var favorite1 = [];        
                          $.each($("input[name='check1']:checked"), function(){                    
                          favorite1.push($(this).val());
                          document.getElementById("countch1").innerHTML=favorite1;
                          });
                          });
                          });
                          </script>
                          

                          【讨论】:

                            【解决方案22】:

                            可以使用我创建的这个函数

                            function getCheckBoxArrayValue(nameInput){
                                let valores = [];
                                let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
                                checked.forEach(input => {
                                    let valor = input?.defaultValue || input?.value;
                                    valores.push(valor);
                                });
                                return(valores);
                            }
                            

                            要使用它,就这样称呼它

                            getCheckBoxArrayValue("type");
                            

                            【讨论】:

                              【解决方案23】:
                               var idsComenzi = [];
                              
                                  $('input:checked').each(function(){
                                      idsComenzi.push($(this).val());
                                  });
                              

                              【讨论】:

                              • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
                              猜你喜欢
                              • 2015-06-28
                              • 1970-01-01
                              • 2012-02-14
                              • 2017-04-03
                              • 2021-12-14
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2016-11-06
                              相关资源
                              最近更新 更多