我有这些复选框:

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

任何想法吗?

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


当前回答

纯JavaScript,不需要临时变量:

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

其他回答

格式:

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

希望它能起作用。

 var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
   return this.value;
}).get();

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

只是说说我的意见,说不定能帮到别人

const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);

我已经有一个jQuery对象,所以我不会选择所有的复选框另一次,这就是为什么我使用jQuery的过滤器方法。然后我把它转换成一个JS数组,我映射数组返回项目的值。

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