【问题标题】:recover all values of checked checkboxes and push them in an array恢复选中复选框的所有值并将它们推送到数组中
【发布时间】:2016-01-25 10:04:52
【问题描述】:

我在我的 php 项目中使用了 twig。

我有一个包含许多复选框的表单。我需要在 javascript 中恢复数组中复选框的所有选中值。

这是javascript:

<script type="text/javascript" charset="utf-8" async defer>
  document.getElementById("{{ value }}").onclick = function() { /* {{ value }} is value of my checkboxe, twig variable it matches like a php variable */
    if ( this.checked ) { /* check if checkboxes are checked */
      var valueChecked = this.value;
      console.log(valueChecked); /* just to display the value for debug */

      var valueArray = []; /* I create an array */
      /* here I need to put all my checkboxes values in allCheckedConfig */
    } else {
      console.log("removed " + this.value ); /* just to debug, check if checkboxes are unchecked */
    }
  };
</script>

如何填写我的valueArray[]

【问题讨论】:

    标签: javascript jquery arrays checkbox twig


    【解决方案1】:

    您可以使用map 函数获取如下数组。

    var elems = document.querySelectorAll('input[type=checkbox]:checked');
    var valueArray = Array.prototype.map.call(elems, function (obj) {
        return obj.value;
    });
    console.log(valueArray)
    

    【讨论】:

    • 看来你的答案是好的。事实上,我需要恢复数组中的所有值,而不仅仅是一次。所以这就是我要找的。谢谢,我验证你的回答。
    • 我的答案将恢复所有值,而不是一次恢复一个。 @french_dev
    【解决方案2】:

    .push 是你所需要的

        var valueArray = [];
        document.getElementById("{{ value }}").onclick = function() { 
        if ( this.checked ) { 
          var valueChecked = this.value;
          console.log(valueChecked);
          valueArray.push(valueChecked);
          console.log(valueChecked); // Should give you the array.
        } else {
          console.log("removed " + this.value ); 
        }
      };
    

    【讨论】:

    • 您的解决方案似乎有效,但如果我选中了许多复选框,valueArray[] 必须返回数组中的所有值,或者当我创建 console.log() 方法时,数组只返回一个值在像["{{value}}"] 这样的时间。你认为数组包含所有检查值吗?
    【解决方案3】:

    如果你的网站上有jQuery,你可以观看serializeArray函数

    【讨论】:

      【解决方案4】:

      试试这个

      var arr=$('input[type=checkbox]:checked').map(function(k,v){return $(v).val();});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-04
        • 1970-01-01
        • 1970-01-01
        • 2018-10-07
        • 1970-01-01
        • 2018-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多