使用jQuery从多个输入获取值数组 [英] Get array of values from multiple inputs using jQuery

查看:66
本文介绍了使用jQuery从多个输入获取值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以让我知道如何从几个输入字段中获取值吗?

Can someone please let me know how to get values from several input fields?

我有一个包含多个输入的列表,如下所示:

I have a list with several inputs like this:

<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>
<li>
<label>Additional Title: </label><input type='text' name='additionaltitlename' ... />
</li>

我有一个使用Javascript的解决方案(在表单提交中):

I have a solution in Javascript (on form submit):

...
var extratitles = document.getElementsByName('additionaltitlename'); 
var str = '';
      for (var i = 0; i < extratitles.length; i++) { 
      str = str + '|' + extratitles.item(i).value;
    } 
}

我如何在JQuery中做同样的事情?

How do I do the same thing in JQuery?

推荐答案

具有相同名称的两个输入无效.如果要执行此操作,可以使用<input name="titles[]">

It's not valid to have two inputs of the same name. If you want to do this, you can use <input name="titles[]">

您可以尝试以下操作:

<input name="titles[]">
<input name="titles[]">
​<button>submit</button>​​​​​​​​​​​​​​​​​​​​​​​

使用此jQuery

// click handler
function onClick(event) {
  var titles = $('input[name^=titles]').map(function(idx, elem) {
    return $(elem).val();
  }).get();

  console.log(titles);
  event.preventDefault();
}

// attach button click listener on dom ready
$(function() {
  $('button').click(onClick);
});

在jsFiddle上查看其工作原理

编辑

此答案为您提供数组中的标题,而不是使用|分隔符的字符串.我个人认为这更有用.

This answer gives you the titles in an array instead of a string using a | separator. Personally, I think this is a lot more usable.

如果您只是提交表单,并且想要支持多个值,请使用另一个答案中所述的.serialize方法

If you're just submitting the form and you want to support multiple values, use the .serialize method as described in the other answer

这篇关于使用jQuery从多个输入获取值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆