2011-05-09 94 views
0

我想将表单中的所有输入合并到一个字符串中,但是我的代码只是覆盖每个循环上的var,只留下了来自最后一个输入的文本形式...我怎样才能解决这个问题?使用jquery获取表单中所有输入的文本

$(':input').each(function() { 
    var output = $(this).val(); 
    $('#output').html(output); 
}); 
+0

尝试用我的解决方案?我也展示了我的答案 – diEcho 2011-05-09 07:30:12

+0

您的解决方案可行,但对于我正在尝试做的事情,我不想创建数组。它确实帮了我,但是,谢谢:) – Giovanni 2011-05-09 07:42:03

回答

4
var output = ''; 
$(':input').each(function() { 
    output += $(this).val(); 
}); 
$('#output').html(output); 

或者你也可以使用.map()功能:

var output = $(':input').map(function() { 
    return $(this).val(); 
}).toArray().join(''); 
$('#output').html(output); 
+0

更紧凑:输出+ = $(this).val(); – Faust 2011-05-09 07:01:13

+0

@Faust,好点。我已更新我的帖子以考虑它。 – 2011-05-09 07:02:10

+0

这正是我需要做的!谢谢! – Giovanni 2011-05-09 07:42:41

1

可尝试

var output = new Array(); 
$(':input').each(function() { 
    output.push($(this).val()); 
}); 
alert(output); 

DEMO

替代:

var output = $(':input').map(function() { 
    return $(this).val(); 
}).get(); 
alert(output); 

DEMO

参考

get

相关问题