我有这些复选框:

<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个是手工编码的(即不是从db中获取的),所以它们可能会在一段时间内保持相同。

我的问题是我如何能得到他们都在一个数组(javascript),所以我可以使用他们,而使AJAX $。使用Jquery发布请求。

任何想法吗?

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


当前回答

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

其他回答

纯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)
}

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

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

$(document).ready(function() {

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

});

</script>

在现代浏览器(不支持IE,遗憾的是在撰写本文时不支持iOS Safari)中使用香草JS的另一种方式是使用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

格式:

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

希望它能起作用。

用这个:

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