I have the HTML code as follows.
<table id="items">
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">-</a></div></td>
<td><input type="text" id="slslno" class="slno"/></td>
<td><input type="text" class="cost"/></td>
<td><input type="text" class="qty"/></td>
<!-- <td><span class="price"></span></td>-->
<td class="price"></td>
<a class="add" id="addrow" href="javascript:;" title="Add a row">+</a> </tr>
</table>
It has a button named "Add a row" which adds more rows dynamically.
Then I have this bind, which calls an update function during blur of the slno field.
function bind()
{
$(".slno").blur(update_unitcost);
}
The function update_unitcost is as follows.
function update_unitcost()
{
var unitprice1=$(this).val();
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
$( ".cost" ).val(unitp);
}
});
}
In the above function, I am able to get the values of with the this
selector, but when it comes to setting the value in the following line,
$( ".cost" ).val(unitp);
It just resets every ".cost
" classes to that particular number. How can I set values to individual delegated rows? I tried the following approach too, but it failed.
var row = $(this).parents('.item-row');
row.find('.cost').val(unitp);
Set a variable in your function to only target the specific .cost
element you wish to update instead of all of them.
function update_unitcost()
{
var unitprice1=$(this).val();
var costItem = $(this).parent().parent().find('td input.cost');
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
costItem.val(unitp);
}
});
}