首页 文章

使用JQuery基于bootstrap-3-typeahead下拉列表将值传递给多个动态创建的控件

提问于
浏览
1

我正在使用Laravel,JQuery和Bootstrap-3-typeahead创建一个发票系统,并创建了一个按钮,使用JQuery在每个表数据中选择列表项时动态添加新表行和文本输入 . 每行中的第一个文本输入具有bootstrap-3-typeahead功能:选择像这样的项目creating invoice tutorial .

从自动完成文本输入下拉列表中选择后,它会自动填充价格,数量并使用JQuery和Ajax GET方法使用以下Typeahead(afterSelect方法)实现为数量输入分配默认值“1” .

This is my html markup screenshot .

My JQuery implementation of boostrap-3-typeahead and generation of auto price, quantity, and total values base on selected item from typeahead dropdown list.

var typeaheadSettings = {
  source: function (query, process) {
    return $.get(url, { query: query }, function (data) {
      console.log(data)
      return process(data);
    });
  },
  afterSelect: function (data) {
    console.log(data.sellPrice);          

    $('#itemPrice').val(data.sellPrice);
    $('#itemQuantity').val('1');
    var price = $('#itemPrice').val();
    var quantity = $('#itemQuantity').val();
    var subtotal = price * quantity;
    $('#itemSubtotal').val(subtotal);
  }
};

The JS code that adds new row on button click:

// Add Row
$(document).on('click', '#btnAddRow', function(event) {
  var i=$('#invoiceTable tbody tr').size();
  html = '<tr>';
  html += '<td><p class="text-center pt-xs"><input type="radio" name="sn" id="sn" value=""></p></td>';
  html += '<td><input type="text" name="productName[]" id="itemName'+ i +'" class="form-control typeahead twitter-typeahead" placeholder="Item name" autocomplete="off" data-fit-to-element="true" data-provide="typeahead"></td>';
  html += '<td><input type="text" name="price[]" id="itemPrice'+i+'" class="form-control text-right" placeholder="Item price" autocomplete="off" readonly></td>';
  html += '<td><input type="number" name="quantity[]" id="itemQuantity'+ i +'" class="form-control text-right" placeholder="Quantity"></td>';
  html += '<td><input type="text" name="subtotal[]" id="itemSubtotal'+ i +'" class="form-control text-right" placeholder="Subtotal" readonly></td>';
  html += '<td class="actions-hover actions-fade text-center"><p><a id="btnDelRow"><i class="fa fa-minus-circle fa-lg text-warning" id="iconDelRow"></i></a></p></td>';
  html += '</tr>';

  $('#invoiceTable tbody').append(html);
  i++;
  $('.typeahead').trigger('added');
});

这是动态添加的行的标记看起来像,ID的后缀为整数"1,2" . 如果动态添加另一行,则整数递增,为所有重复控件提供唯一ID . dynamically added tr screenshot

问题是,当我通过单击上图中显示的“添加新行”按钮动态添加第二个控件时,动态添加的价格和数量输入控件不会获得新生成的值 . 相反,值显示在第一个已定义的行上 . 当我添加第3行以及更多时,会发生同样的事情 . 如果有人可以帮助我,我会很高兴我可以将下拉列表项目选中的值传递给正确或适当的输入 .

2 回答

  • 0

    您正在使用的HTML选择器似乎是一个ID选择器,每个文档应该是唯一的 . 这可以解释为什么会发生这种情况 .

  • 0

    似乎值出现在第一个定义的行上,因为您只将它们的ID编码到typeaheadSettings.afterSelect(...)函数中:

    $('#itemPrice').val(data.sellPrice);
        $('#itemQuantity').val('1');
        var price = $('#itemPrice').val();
        var quantity = $('#itemQuantity').val();
        var subtotal = price * quantity;
        $('#itemSubtotal').val(subtotal);
    

    您可能应该重构该函数,以便它可以使用其他自动生成的ID,如 #itemPrice1#itemSubtotal2 ,...

相关问题