admin管理员组文章数量:1356554
I have a form that contains a couple of checkboxes. After send this form I would need these checkboxes (the values) to a javascript array.
Could anyone give me a favor, please, how to do?
I have a form that contains a couple of checkboxes. After send this form I would need these checkboxes (the values) to a javascript array.
Could anyone give me a favor, please, how to do?
Share Improve this question edited Sep 13, 2011 at 10:42 betamax 14.1k9 gold badges42 silver badges55 bronze badges asked Sep 13, 2011 at 10:26 user1946705user1946705 2,88814 gold badges43 silver badges58 bronze badges4 Answers
Reset to default 3var form = document.getElementById("yourformname"),
inputs = form.getElementsByTagName("input"),
arr = [];
for (var i = 0, max = inputs.length; i < max; i += 1) {
// Take only those inputs which are checkbox
if (inputs[i].type === "checkbox" && inputs[i].checked) {
arr.push(inputs[i].value);
}
}
with jquery you could do something like this:
var checkboxArr=[];
$('input[type=checkbox]').each(function(){
checkboxArr.push(this);
});
Untested and not sure how this would work in pure js, maybe it can point you in the right direction
var values = [],
inputs = document.getElementsByTagName("input");
for (var i = inputs.length -1 ; i>= 0; i--)
if (inputs[i].type === "checkbox" && inputs[i].checked)
values.push(inputs[i].value);
for pure JS.
You can test the following function on jsfiddle:
function getCheckboxes(form_id, name) {
// returns array of checked checkboxes with 'name' in 'form_id'
var form = document.getElementById(form_id);
var inputs = form.getElementsByTagName("input");
var values = [];
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type === "checkbox" &&
inputs[i].name === name &&
inputs[i].checked)
{
values.push(inputs[i].value);
}
}
return values;
}
本文标签: javascriptHow to add the values from checkboxes to an arrayStack Overflow
版权声明:本文标题:javascript - How to add the values from checkboxes to an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744006666a2574825.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论