我有这些复选框:

<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发布请求。

任何想法吗?

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


当前回答

在现代浏览器(不支持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

其他回答

如果你想使用一个普通的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>

在Javascript中,它是这样的(演示链接):

// 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;
}   

用这个:

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

函数selectedValues(避署){ Var arr = []; For (var I = 0;I < ele.length;我+ +){ 如果(避署[我]。Type == 'checkbox' && ele[i].checked){ arr.push(避署[我]。value); } } 返回arr; }

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