简体   繁体   English

基于select2的jquery填写表单字段

[英]jquery fill form field based on select2

I'm building a B2B ordering app and am trying to fill form fields based on select2 selection.我正在构建一个 B2B 订购应用程序,并尝试根据 select2 选择填写表单字段。 On the table, there's an "ADD" button, to add more lines as needed.在桌子上,有一个“添加”按钮,可以根据需要添加更多行。 So when you select a product, (with select2 dropdown) it should go and fetch pricing and product-related discount from the database.因此,当您选择产品时,(使用 select2 下拉菜单)它应该从数据库中获取定价和与产品相关的折扣。 This works for the first line/row.这适用于第一行/行。
Any subsequent rows do not fetch price and discount from the database.任何后续行都不会从数据库中获取价格和折扣。

EDIT:编辑:
To clarify a bit more - if you click Add button, multiple rows get added without errors.澄清一点 - 如果您单击“添加”按钮,则会添加多行而不会出错。 The price fetching script simply does not fetch any data after the first row.价格获取脚本在第一行之后不会获取任何数据。

Any help would be appreciated任何帮助,将不胜感激

Add Row code:添加行代码:

$(".custom-select").select2();
            let row_number = {{ count(old('products', [''])) }};
            $("#add_row").click(function(e) {
                e.preventDefault();
                var options = $("#products_table tbody tr:first").find("[name='StockItem[]']").html();
                var cloned = $("#products_table tbody tr:first").clone().show();

                $(cloned).find("td:first").html('<select name="StockItem[]" class="select2 form-control mb-3 custom-select" style="width: 100%; height:36px;">' + options + '</select>')
                $(cloned).find("input").val("")

                $('#products_table tbody').append('<tr id="product' + (row_number + 1) + '">' + $(cloned).html() + '</tr>');
                $("select").select2();
                row_number++;
            });

Fetching price/discount获取价格/折扣

$('#product').on('keyup change', function(){
    var product_id = $("#product").val();
    $.post('/orders/getprice/' + product_id,
       function (data) {
          $('#UnitPrice').val(data.SellingPrice);
          $('#Discount').val(data.DiscountPercentage);
    });
})

Question doesn't seem to be clear enough, but I think what you are getting into is because of var product_id = $("#product").val();问题似乎不够清楚,但我认为您正在讨论的是因为var product_id = $("#product").val(); while id you are generating in html is id="product' + (row_number + 1) + '"而你在 html 中生成的id="product' + (row_number + 1) + '"id="product' + (row_number + 1) + '"

$('#products_table tbody').append('<tr class="product_abc" id="product' + (row_number + 1) + '">' + $(cloned).html() + '</tr>');

$('.product_abc').on('keyup change', function(e){
    console.log(e.target); // this will be your button which is clicked.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM