我有这些复选框:

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

任何想法吗?

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


当前回答

Array.from($(".yourclassname:checked"), a => a.value);

其他回答

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

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");

在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 yourArray=[];
        $("input[name='ordercheckbox']:checked").each(function(){
            yourArray.push($(this).val());
        });
        console.log(yourArray);
var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

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

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