我是 Jquery 和 Rails 的初学者。
我正在尝试从 Rails Controller 获取数据并将其设置为位于动态表中的文本字段。
HTML
<tbody id="template">
<tr>
<td>
<select name="order[order_placed][][itemname]" id="order_place_id" class="form-control delete-comment" style="width: 300px">
<option value=""></option>
<% Item.all.each do |item| %>
<option value="<%= item.item_name %>">
<%= item.item_name %>
</option>
<% end %>
</select>
</td>
<td><input name="order[order_placed][][quantity]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][unitprice]" type="text" size='10' class="form-control" /></td>
<td><input name="order[order_placed][][tax]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][discount]" type="text" size='10' class="form-control"/></td>
<td><input name="order[order_placed][][itemtotalprice]" type="text" size='10' class="form-control" /></td>
<td>
<button type="button" class="btn btn-default btn-sm sub" onClick="$(this).closest('tr').remove();">
<span class="glyphicon glyphicon-minus"></span>
</button>
</td>
</tr>
</tbody>
<小时/>
JS
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
$.ajax({
url: "/items/getdata",
type: 'get',
data: {data_value: $(this).val()},
dataType: 'json',
success: function (data) { $(this).closest('tr').next('td').next('td').next('td').find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$('input[name="order[order_placed][][tax]"]').val(data.tax);
$('input[name="order[order_placed][][discount]"]').val(data.discount);
}, error: function () {
alert('error');
}
});
});
<小时/>
如果我们直接分配数据,数据将被正确获取并设置到文本框(data.tax
和 data.discount
设置正确)。
由于表格是动态的,我尝试通过查找最接近的 tr
元素来放置数据,然后再查找下一个 td
(选择元素)下一个 td
(数量)再次td
(单价)。 [这是我想要放置数据的文本字段。]
但这不能正常工作。
有人可以帮忙吗?
提前谢谢...!!!
最佳答案
this
并不引用 success
回调中的当前元素,因此 $(this)
将不起作用。
您可以将TR
的引用缓存在一个变量中,该变量可以在success
回调中使用
$(document).on('change', 'select', function() { //var url = $('.delete-comment').attr('data-url');
//Keep a reference of current element
var tr = $(this).closest('tr');
$.ajax({
...
success: function(data) {
tr.find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
tr.find('input[name="order[order_placed][][tax]"]').val(data.tax);
tr.find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
<小时/>
或者,您可以设置$.ajax()
的context
选项
$(document).on('change', 'select', function() {
$.ajax({
...
context: $(this).closest('tr'), // Set context to TR
success: function(data) {
$(this).find('input[name="order[order_placed][][unitprice]"]').val(data.unit_price);
$(this).find('input[name="order[order_placed][][tax]"]').val(data.tax);
$(this).find('input[name="order[order_placed][][discount]"]').val(data.discount);
},
});
});
关于javascript - Jquery动态表中最接近的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48406330/