我有这些复选框:

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

任何想法吗?

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


当前回答

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

其他回答

var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

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

在MooTools 1.3(撰写本文时的最新版本)中:

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

纯JavaScript,不需要临时变量:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.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");

ES6版本:

const values = Array
  .from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);

function getCheckedValues() { return Array.from(document.querySelectorAll('input[type="checkbox"]')) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); } const resultEl = document.getElementById('result'); document.getElementById('showResult').addEventListener('click', () => { resultEl.innerHTML = getCheckedValues(); }); <input type="checkbox" name="type" value="1" />1 <input type="checkbox" name="type" value="2" />2 <input type="checkbox" name="type" value="3" />3 <input type="checkbox" name="type" value="4" />4 <input type="checkbox" name="type" value="5" />5 <br><br> <button id="showResult">Show checked values</button> <br><br> <div id="result"></div>