如何分别从动态生成的文本框中获取值?

How to get values from dynamically generated text box separately?

$.ajax({            
  type: "POST",
  contentType: 'application/json;charset=utf-8',
  dataType:'json',
  url: 'generatequotations',
  data: JSON.stringify(),
  success: function(result) {
    //  alert("success"); 
    console.log(result);
    $.each(result, function(i, item) { 
      tr = $('<tr/>');   
      tr.append($("<td/>").html('<input type="text" name="unit_price" id="unit_price"/>'));
      tr.append($("<td/>").html('<input type="text" readonly="true" name="total" id="total"/>'));
      $('#tbl_items').append(tr);
    });   
  }
});

<body>
<table id="tbl_items"></table>
</body>

假设上面的代码将在table中生成10个'unit_price'文本框,我需要的是分别获取这10个文本框的值以供进一步计算。帮我极客...

Link到截图http://oi62.tinypic.com/255hslc.jpg

这两行是动态生成的我想在相应的总('total')个文本框内获取每个文本框('unit_price')

将您的文本框选择器从 id 更改为 class,因为您必须取多个值。

<input type="text" name="unit_price" class="unit_price"/>
<input type="text" name="unit_price" class="total"/>

jQuery

total = 0;
$(".unit_price").each(function(){
   //Find total column and put unit_price value in total column
   $(this).closest(".total").val($(this).val());  
});

您可以使用两种不同的方式获取该值。

首先:当你在行中添加一个文本框时,将它的id设为"id"+ i,这将为每个文本框提供不同的id,同样的事情也可以应用于行。

其次:如果您为所有文本框提供相同的 ID(您目前正在这样做),那么您可以使用 "this" 找到它的值。 $(this).closest('input'), $(this).siblings(),$(this).parent() 所有这些都将帮助您获得文本框的价值。

无论您尝试什么方法,请在浏览器控制台上尝试,特别是在 Chrome 上,这将对您有很大帮助。