Reputation: 519
i need to add a ajax data in to input fields with same id. new rows can be added by clicking add row button. all rows generated with same ids and classes. i'm trying to add ajax data in to text fields in change of first select box on each row. how do i set data only for the changed row.
Dynamic form
<tr>
<td>
<select class="form-control itemId" id="itemId" required="required" name="item_id[]">
<option value="" selected="selected">Select an item</option><option value="1">Toyota Front Buffer</option>
<option value="2">Mitsubishi Lancer Right Door</option>
</select>
</td>
<td>
<input class="form-control item_description" id="item_description" placeholder="Not Required | Optional" name="item_description[]" type="text">
</td>
<td>
<input class="form-control" placeholder="Add Units" id="units" required="required" name="units[]" type="text">
</td>
<td>
<input class="form-control" placeholder="Add Rate" id="rate" required="required" name="rate[]" type="text">
</td>
<td>
<input class="form-control" id="amount" placeholder="Add Hrs and Rate" name="amount[]" type="text">
</td>
</tr>
<tr>
<td>
<select class="form-control itemId" id="itemId" required="required" name="item_id[]">
<option value="" selected="selected">Select an item</option><option value="1">Toyota Front Buffer</option>
<option value="2">Mitsubishi Lancer Right Door</option>
</select>
</td>
<td>
<input class="form-control item_description" id="item_description" placeholder="Not Required | Optional" name="item_description[]" type="text">
</td>
<td>
<input class="form-control" placeholder="Add Units" id="units" required="required" name="units[]" type="text">
</td>
<td>
<input class="form-control" placeholder="Add Rate" id="rate" required="required" name="rate[]" type="text">
</td>
<td>
<input class="form-control" id="amount" placeholder="Add Hrs and Rate" name="amount[]" type="text">
</td>
</tr>
Ajax code
$("#dynamic-tbl").on('change', 'select', function(e){
var item_id = e.target.value;
var self = this;
$.get('/ajax-item?item_id=' + item_id, function(data){
$.each(data, function(index, itemObj){
$(this).closest('#item_description').val(itemObj.name);
$(this).closest('#rate').val(itemObj.sale_price);
});
});
});
Upvotes: 0
Views: 1114
Reputation: 40639
Try this.,
$.each(data, function(index, itemObj){
$(self) // use self not this
.closest('tr') // get the parent(closest) tr
.find('input[name="item_description[]"]')// now find the item_description by name as id must be unique
.val(itemObj.name);
$(self)
.closest('tr')
.find('input[name="rate[]"]')
.val(itemObj.sale_price);
});
Upvotes: 1