jQuery - 从动态创建的输入中获取值

时间:2012-09-11 16:51:04

标签: jquery jquery-selectors

请在此处查看演示:http://jsfiddle.net/9pR87/28/

  1. 添加输入 - 使用新输入添加新行
  2. 获取价值 - 获得最后添加的输入值
  3. 我正在创建一些额外的行(发票元素),但是当我想使用获取动态创建的输入中的值时,输入值始终为undefined。为什么呢?

    为什么jQuery无法找到动态创建输入的值?

2 个答案:

答案 0 :(得分:6)

我认为这足以满足您的需求:

$('#GetValue').click(function() {
    var i = $('table tbody tr').length-1; // subtract 1 for correct indexing
    alert($('#ItemPrice-' + i).val());
    // OR
    alert( $('[id^=ItemPrice]:last').val() );
});

<强> Demo

根据jsfiddle的评论

问题是:

tableRow += '<td><input type="text" name="ItemPrice[]" id="ItemPrice-' + i + ' " 
                                                                              ^--- an space
placeholder="Item Price"></td>';

tableRow += '<td><input type="text" name="NumberOfItems[]" id="NumberOfItems-' + i + ' " 
                                                                                      ^-- an space
placeholder="Number Of Items"></td>';

<强> Here is update and working code

答案 1 :(得分:2)

$('#GetValue').click(function() {

    var i = $('table tbody tr').length; // this line is the issue

    alert($('#ItemPrice-' + i).val());

});​

我已经在你的代码中复制了这个函数,它给你提供了问题。我突出显示的一行应该是:

var i = $('table tbody tr').length-1;

这是因为Javascript中的数组是0索引的,这意味着它们从零开始向上计数。这意味着如果你想得到数组的最后一个元素,你需要找到数组的长度并减去一个,正如我所展示的那样。

这一行:

alert($('#ItemPrice-' + i).val());

实际上返回一个数组,从0开始计数。这就是为什么将元素放在array.length位置会返回undefined。

Here's a working demo作为证据。

相关问题