我有这些复选框:

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

任何想法吗?

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


当前回答

在勾选时添加复选框的值,在勾选时减去该值

$('#myDiv').change(function() { var values = 0.00; { $('#myDiv :checked').each(function() { //if(values.indexOf($(this).val()) === -1){ values=values+parseFloat(($(this).val())); // } }); console.log( parseFloat(values)); } }); <div id="myDiv"> <input type="checkbox" name="type" value="4.00" /> <input type="checkbox" name="type" value="3.75" /> <input type="checkbox" name="type" value="1.25" /> <input type="checkbox" name="type" value="5.50" /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

其他回答

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

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

你可以尝试这样做:

$('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,

使用注释if块,以防止添加值已经在数组中,如果你使用按钮点击或其他东西来运行插入

$('#myDiv').change(function() { var values = []; { $('#myDiv :checked').each(function() { //if(values.indexOf($(this).val()) === -1){ values.push($(this).val()); // } }); console.log(values); } }); <div id="myDiv"> <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" /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

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

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

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