首页 > 解决方案 > Ajax 数据未正确分配给具有相同类的 jQuery 输入

问题描述

我正在开发发票系统,其中费率(金额)值会在更改产品(项目)时自动更改。

我面临的问题是在更改第一个产品时,所有其余的产品费率都更改为第一个项目的费率。

在选择产品时更改费率的代码。(jQuery)

//Values and Inputs
$(document).on('change', '.Item', function() {
    var Item = $('.Item').closest('.Item').val();
    $.ajax({
        type: 'GET',
        url: 'AjaxPrice.php',
        data: { Item: Item },
        success: function(response) {
            $('.Rate').val(response);
        }
    });
});

预定义表代码

<tbody class="TableBody">
  <tr>
    <td style="width: 220px">
      <input type="text" class="form-control Item" name="Item" id="Item" placeholder="Nombre del producto" required autocomplete="off">
    </td>
    <td>
      <input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>
    </td>
    <td>
      <input step="2" type="number" class="form-control text-right Rate" min="1" id="Rate" placeholder="0.00" readonly>
    </td>
    <td>
      <input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">
    </td>
    <td>
      <input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>
    </td>
    <td>
      <button type="button" class="btn btn-danger DelRow">Delete</button>
    </td>
  </tr>

</tbody>

添加新项目的代码

$('#AddNewItem').click(function() { $('.TableBody').append(`
<tr>
  <td style="width: 220px">
    <input type="text" class="form-control Item" name="Item" id="Item" placeholder="Nombre del producto" required autocomplete="off">
  </td>
  <td>
    <input type="number" name="QTV" min="1" name="QTV" id="QTV" class="form-control text-right" placeholder="00" required>
  </td>
  <td>
    <input step="2" type="number" class="form-control text-right Rate" min="1" id="Rate" placeholder="0.00" readonly>
  </td>
  <td>
    <input step="any" id="Disc" name="Disc" type="number" min="0" name="" class="form-control text-right" placeholder="00">
  </td>
  <td>
    <input type="text" name="SubTotal" class="form-control text-right" id="Total" placeholder="Total" readonly>
  </td>
  <td>
    <button type="button" class="btn btn-danger DelRow">Delete</button>
  </td>
</tr>
`); });

任何帮助将不胜感激。

标签: javascriptjqueryhtmlcss

解决方案


选择行中的输入。您正在选择第一个输入

$(document).on('change', '.Item', function() {
    var item = this.value // get the item that was changed
    var row = $(this).closest("tr")  // get the table row the item is in
    var rate = row.find(".rate") // find the rate input in the row
    $.ajax({
        type: 'GET',
        url: 'AjaxPrice.php',
        data: { Item: Item },
        success: function(response) {
          rate.val(response);
        }
    });
});

推荐阅读