如何使用 javascript/jquery 获取文本框数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3520565/
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
How to fetch textbox array value using javascript/jquery
提问by bin
I have an array of text inputs like this:
我有一个像这样的文本输入数组:
<input type="textbox" name="mobileno[]"><br>
<input type="textbox" name="mobileno[]"><br>
<input type="textbox" name="mobileno[]"><br>
They are generated at run time using an "add more" button.
它们是在运行时使用“添加更多”按钮生成的。
Is there a way I can use jQuery to fetch the text input value and pass it in ajax request?
有没有办法可以使用 jQuery 来获取文本输入值并在 ajax 请求中传递它?
I have created an ajax request but I'm not able to fetch the value of text input array in name=value pattern.
我创建了一个 ajax 请求,但我无法以 name=value 模式获取文本输入数组的值。
回答by Sarfraz
You can do like this:
你可以这样做:
$('input[name="mobileno[]"]').each(function(){
alert($(this).val());
});
The ^=finds elements whose name starts withmobilenotext and later eachis used to loop over all the elements to get their value.
该^=认定元素的名字开始与mobileno文字,后来each被用于遍历所有的元素来获得自己的价值。
More Info:
更多信息:
回答by Murugesh
Try this:
试试这个:
var text= new Array();
$("input[name='mobileno[]']").each(function(){
text.push($(this).val());
});
If u alert the variable text you will get the comma separated output.
如果您警告变量文本,您将获得逗号分隔的输出。
回答by Reigel
var data = $('input[name="mobileno[]"]').map(function(){
return this.name + '=' + this.value;
}).get().join('&');
alert(data);
this will give you a something like mobileno[]=value&mobileno[]=value&mobileno[]=value.
You can then pass it in your ajax request.
这会给你一个类似的东西mobileno[]=value&mobileno[]=value&mobileno[]=value。然后您可以在您的 ajax 请求中传递它。
回答by RoToRa
First off: That's not an "array of textbox[es]". There is no such thing as an array in HTML. It's just multiple text boxes which all happen to have the same name, and that name just happens to have square brackets in the name. The square brackets in the name have no special meaning in HTML. (PHP needs them, but that's a whole other thing).
首先:那不是“文本框数组[es]”。HTML 中没有数组这样的东西。它只是多个文本框,它们都碰巧具有相同的名称,而该名称恰好在名称中带有方括号。名称中的方括号在 HTML 中没有特殊含义。(PHP 需要它们,但这是另一回事)。
Second: type="textbox"is wrong. It's just type="text". You are lucky it's working because "text"is the default value that browsers fall back to when finding an invalid value such as textbox.
第二:type="textbox"错了。这只是type="text"。您很幸运它可以工作,因为这"text"是浏览器在找到无效值(例如textbox.
If you need to get the vales of a form in the standard name=value pattern (separated with &) jQuery provides the serializemethod for forms:
如果您需要在标准的 name=value 模式(以 分隔&)中serialize获取表单的值,jQuery 提供了表单的方法:
alert($("#your-form-id").serialize());

