如何更改表的当前行中元素的值

时间:2016-02-29 12:55:25

标签: jquery

HTML

<form action="#" method="POST" id="delivery_form">
    <h3>Delivery Schedule</h3>
    <table>
        <tr><th>Item</th><th>Quantity</th><th>Amount</th><th>Date Start</th><th>Date End</th><th></th></tr>
        <tr class="tr_clone">
            <td>
                <select name="item[]" id="item_name" onchange="getval(this);">

                </select>
            </td>
            <td><input type="number" name="qty[]" /></td>
            <td><input type="text" name="amt[]" /></td>
            <td><input type="date" name="date_start[]" /></td>
            <td><input type="date" name="date_end[]" /></td>
            <td><input type="text" name="count" value="1"/><input type="button" name="add" value="Add" class="tr_clone_add"></td>
        </tr>
        <tr>
            <td colspan="6">
            <input type="text" name="contract_id" value="" />
            <input type="submit" value="Submit" onclick="submit_delivery()" />
            </td>
        </tr>
    </table>

</form>

单击add按钮时,将插入新行。现在的问题如下:

1)当选择框被更改时,我将获得ID,并从db获取此项目的PRICE并显示在相应行的AMT文本框中。

SCRIPT:

function getval(sel) {
       //alert(sel.value);//this gets the ID of the select box item

       var data;
       $.ajax({
              type: "POST",
              dataType: "json",
              url: "../admin/get_item.php?item_id="+sel.value,
              data: data,
              success: function(data) {

                console.log(data);
                for(var i=0;i<data.length;i++)
                    {
                        alert(data[i].price);//price for the id obtained

                       //Here's the problem. The below would change price  for all amount textbox. I need to change only for the related row. How to do this, please?
                        //$("input[name^=amt]").val(data[i].price);

                    }
              }
            });
    }

1 个答案:

答案 0 :(得分:1)

你可以用,

$("input[name^=amt]", $(sel).closest("tr")).val(data[i].price);

在你的ajax成功callback内,以定位与当前行相关的元素。