Javascript 获取jquery中所有具有相同名称属性的文本框的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13916661/
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 15:07:16  来源:igfitidea点击:

Get values of all textboxes with same name attributes in jquery

javascriptjquery

提问by Developer

I need to get values of all textboxes with same name attributes using jquery.

我需要使用 jquery 获取具有相同名称属性的所有文本框的值。

<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">

How can I get all values of textbox text[]and compare it using jquery.

如何获取文本框text[] 的所有值并使用 jquery 进行比较。

I tried using

我尝试使用

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

but am no successful.

但我没有成功。

回答by undefined

You can use mapmethod and store the values into an array.

您可以使用map方法并将值存储到数组中。

$(function(){
   var values = $('input[name="text[]"]').map(function(){
       return this.value
   }).get()
})

http://jsfiddle.net/UugWW/

http://jsfiddle.net/UugWW/

回答by Magus

This one should work :

这个应该工作:

$('input[name="text[]"]');

You can loop on it to get all values.

您可以循环它以获取所有值。

$('input[name="text[]"]').each(function() {
    alert($(this).val());
});

回答by Bruno

Let's split the requirement into smaller problems.

让我们将需求拆分为更小的问题。

First you want to select all those inputs.

首先,您要选择所有这些输入。

var $inputs = $("input[name='text[]']")

It returns a jQuery object, containing all the input named text[]. You also might not need to use square brackets into the name.

它返回一个 jQuery 对象,其中包含所有名为text[]. 您也可能不需要在名称中使用方括号。

var inputs = $inputs.get();

Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.

将匹配的元素提取到一个普通的 Array 中,以便我们现在可以访问 Array 的原型方法,例如Array.prototype.map

var values = inputs.map(function takeValue(input) {
    return input.value;
});

回答by dsgriffin

Use a selector like this:

使用这样的选择器:

$('input[type="text"][name="text[]"')

回答by Jithin.N

var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
 textvalue= textvalue + document.getElementsByName("text").item(i).value; 
}
alert(textvalue);