我正在尝试向Select添加.on('change')
事件,这是动态插入行的一部分。 console.log(data);
正在返回正确的数据集。我无法弄清楚如何让它在选择被激活的同一行上选择#prototypePrice
。
$(document).ready(function() {
$('#lineitems').on('change', '.prototypeSelect', function() {
var that = $(this);
$.get('getItem.php?q=' + $(this).val(), function(data) {
console.log(data);
var objItem = jQuery.parseJSON(data);
that.closest('#prototypePrice').val(objItem.item_price); //this is wrong
});
});
});
这是原型行:
<div style="display:none;" id="rowPrototype" >
<div>
<select id="prototypeSelect" class="prototypeSelect">
//Select Options
</select>
</div>
<div>
<input type="text" id="prototypePrice" class="prototypePrice">
</input>
</div>
</div
以下是插入原型行的JQUERY:
var objLineitem;
$(document).ready(function() {
$('.invoiceClass').click(function() {
$.get('getlineItems.php?q=' + $(this).attr("name") , function(data) {
console.log(data);
var objLineitem = $.parseJSON(data);
for (i=0; i < objLineitem.length; i++) {
var newRow = $('#rowPrototype').clone();
newRow.show();
$('#lineitems').append(newRow);
newRow.attr('id', 'insertedRow');
newRow.attr('class', 'row insertedPrototypeRow');
答案 0 :(得分:0)
closest
遍历DOM树并获得第一个匹配的祖先。
在您的情况下,您要设置值的输入是div的子节点,它是父{div} {div}的父节点的下一个直接兄弟节点
所以你可以使用:
that
而不是:
that.closest('div').next().find('.prototypePrice').val(objItem.item_price);
答案 1 :(得分:0)
这是改变选择的下一个兄弟的孩子,所以
$(document).ready(function () {
$('#lineitems').on('change', '.prototypeSelect', function () {
var that = $(this);
$.get('getItem.php?q=' + $(this).val(), function (data) {
console.log(data);
var objItem = jQuery.parseJSON(data);
that.parent().next().find('.prototypePrice').val(objItem.item_price); //this is wrong
});
});
});
演示:Fiddle
另请注意,如果给定的结构重复,那么您不应该对这些元素使用id
,因为它会创建重复的ID
此外,input
是一个自闭元素,因此没有</input>
答案 2 :(得分:0)
您可以为每一行使用唯一ID。然后使用该ID
进行搜索会更容易 $('#'+rowID + " .prototypePrice").val(newValue)
或
您可以使用行上下文
$(".prototypePrice",that.parents('#rowPrototype')).val(newVal)
如果'prototypePrice'正在重复,则同意arun然后不要将它用作id.Also rowPrototype。它不能用作班级
$(".prototypePrice",that.parents('.rowPrototype')).val(newVal)