如何获取与 javascript 数组同名的输入元素的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7157632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:05:40  来源:igfitidea点击:

How do I get values of input element with the same name as an javascript array?

javascriptjquery

提问by Alwayz Change

I want to get values of the input element that those elements are under the same name, name="items[]"
for example:

我想获取输入元素的值,这些元素具有相同的名称,例如 name="items[]"

<div>...<input type="text" name="items[]" value="1" /></div>
<div>...<input type="text" name="items[]" value="2" /></div>
<div>...<input type="text" name="items[]" value="3" /></div>

And I wish to get the result something like:

我希望得到类似的结果:

[1, 2, 3] //that store in an javascript variable.

Do I need to do a loop to access all the elements to get its value? Please give me a good solution either javascript or JQuery.
Thanks

我是否需要循环访问所有元素以获取其值?请给我一个好的解决方案,无论是 javascript 还是 JQuery。
谢谢

回答by Igor Dymov

var values = [];
$("input[name='items[]']").each(function() {
    values.push($(this).val());
});

回答by Graham

JavaScript only:

仅 JavaScript:

var values = [];
var fields = document.getElementsByName("items[]");
for(var i = 0; i < fields.length; i++) {
    values.push(fields[i].value);
}

Warning, see: getElementsByName in IE7

警告,请参阅:IE7 中的 getElementsByName

回答by Jochem

Or use jQuery's map function:

或者使用 jQuery 的 map 函数:

$("div input[name='items[]']").map( function() { return $(this).val(); } ).get();