我有这些复选框:

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

任何想法吗?

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


当前回答

格式:

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

希望它能起作用。

其他回答

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

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

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>

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

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

按输入名称选择复选框

var category_id = [];

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