3

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);
Ashif Shereef
  • 454
  • 1
  • 8
  • 24

1 Answers1

1

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);        
      }
    });                
}
CreMedian
  • 763
  • 5
  • 15
  • Would you please explain to me what $(this).parent().parent().find('td input.cost'); does? – Ashif Shereef Jan 28 '16 at 16:43
  • 1
    sure. the first .parent() looks at the containing element the function is acting upon, which would be a . The next .parent() looks outside that element to the main container (the ). With this new context, the .find() function then can get at what you really want, the and its child input – CreMedian Jan 28 '16 at 16:48