我有这些复选框:
<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,你可以像@zahid-ullah那样做,但要避免循环:
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
ES6中的相同代码看起来更好:
var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
document.getElementById('serialized').innerText = JSON.stringify(values);
}
label {
display: block;
}
<label>
<input type="checkbox" name="fruits[]" value="banana">Banana
</label>
<label>
<input type="checkbox" name="fruits[]" value="apple">Apple
</label>
<label>
<input type="checkbox" name="fruits[]" value="peach">Peach
</label>
<label>
<input type="checkbox" name="fruits[]" value="orange">Orange
</label>
<label>
<input type="checkbox" name="fruits[]" value="strawberry">Strawberry
</label>
<button onclick="serialize()">Serialize
</button>
<div id="serialized">
</div>