简体   繁体   中英

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. 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. 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(); while id you are generating in html is 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.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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