我有这些复选框:

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

任何想法吗?

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


当前回答

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

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

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

其他回答

你可以尝试这样做:

$('input[type="checkbox"]').change(function(){
       var checkedValue = $('input:checkbox:checked').map(function(){
                return this.value;
            }).get();         
            alert(checkedValue);   //display selected checkbox value     
 })

Here

$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function()  looping on all checkbox,

这是我的代码,同样的问题,有人也可以尝试这个。 jquery

<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];        
$.each($("input[name='check1']:checked"), function(){                    
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>

格式:

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

希望它能起作用。

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

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>