JQuery从输入获取表行值并保存到数组

时间:2014-08-05 09:50:55

标签: jquery html arrays row

我在td中有一个包含输入字段的表。如何从输入字段中获取值(通过按钮单击)并使用JQuery将它们存储到数组(一行)中?所以有不同的行有不同的上下文,我想逐行处理,所以我必须按类识别这些行,依此类推。

谢谢!

更新:我希望数组中test1的值,数组中的test2等等。

<tr class="test1">
 <td>
      <input type="text" name="test">
      <input type="text" name="test">
      <input type="text" name="test">
 </td>
</tr>

<tr class="test2">
 <td>
      <input type="text" name="test">
      <input type="text" name="test">
      <input type="text" name="test">
 </td>
</tr>

2 个答案:

答案 0 :(得分:2)

$("#button").click(function(){

    var array = [];

    $('#table tr').each(function() {

        var values = [];

        $(this).find("input").each(function(){
             values.push(this.val());
        });

        array.push(values);

    });
})

然后你可以通过array.pop();

来获取项目

答案 1 :(得分:0)

你可以这样做:

HTML:

<table>
    <tr class="test1">
        <td>
            <input type="text" name="test" />
            <input type="text" name="test" />
            <input type="text" name="test" />
            <td>
                <input type="button" class="GetValues" value="GetValues" />
            </td>
        </td>
    </tr>
    <tr class="test2">
        <td>
            <input type="text" name="test" />
            <input type="text" name="test" />
            <input type="text" name="test" />
        </td>
        <td>
            <input type="button" class="GetValues" value="GetValues" />
        </td>
    </tr>
</table>

JQUERY:

$(".GetValues").click(function () {
    var test1 = $(this).closest(".test1").find("input:text").map(function () {

        return $(this).val();

    });

    console.log(test1)

})

FIDDLE:

http://jsfiddle.net/XFy46/