获取位于特定类中的所有文本字段值

时间:2011-07-20 07:15:53

标签: jquery

我想获取位于单个类名中的所有字段..例如我的代码如。

<div class="test">
 <input type="text" class="text-field" />
 <input type="text" class="text-field" />
 <input type="text" class="text-field" />
 <input type="text" class="text-field" />
</div>

<div class="test">
 <input type="text" class="text-field" />
 <input type="text" class="text-field" />
 <input type="text" class="text-field" />
 <input type="text" class="text-field" />
</div>

我希望得到each loop,在其中返回此类中的文本字段值。 有什么建议 .. (我是jquery的新手)

5 个答案:

答案 0 :(得分:74)

试试这个:

$(".test .text-field")

修改

要获得值,请尝试以下方法:

$(".test .text-field").each(function() {
    alert($(this).val());
});

答案 1 :(得分:40)

如果您希望将所有值都放入数组中,则可以执行以下操作:

var texts= $(".test .text-field").map(function() {
   return $(this).val();
}).get();

答案 2 :(得分:0)

你试过这个:

$(".test input[type=\"text\"]")

答案 3 :(得分:0)

来自cwallenpoole的答案应该起作用

$.each( $(".test input[type=\"text\"]"), function(index, ele){
   alert( ele.val());
 });

答案 4 :(得分:0)

这是获取输入值数组的另一种方法:

Array.from($('.test .text-field').get(), e => e.value)

或者:

[].map.call($('.test .text-field').get(), e => e.value)