ajax数据到具有相同id的输入字段

时间:2016-02-01 05:17:08

标签: javascript php jquery html ajax

我需要在具有相同id的输入字段中添加ajax数据。  单击添加行按钮可以添加新行。使用相同的ID和类生成的所有行。我正在尝试在每行的第一个选择框的更改中将ajax数据添加到文本字段中。我如何仅为更改的行设置数据。

动态表单

<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代码

$("#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);
        });
    });
});

1 个答案:

答案 0 :(得分:1)

试试这个。,

$.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);
});