jquerylaraveljquery-select2-4

How To Get Data From Api And Display It To Related Control In Dynamic Table When User Select An Item From Select2 In Laravel?


How To Get Data From Api And Display It To Related Control In Dynamic Table When User Select An Item From Select2 In Laravel?

I am using Laravel with select2. In my form I am adding select2 and input-text dynamically and getting select2 data from server using ajax request and its working fine. Here I am using select2 for 'Ledger' and input-text for 'Balance' in dynamic table. Their have a 'Add' button to add new row in table. I want to call an Api to get Ledger balance and display it on balance input-text when user select an item from select2 accordingly.

I am using below code when select2 initialize and it is working fine for newly created row.

 $('.select2_el').on('select2:select', function (e) {               
                var query= $(this).val();
                console.log(query);    
            });

But when i change the item of pre selected item from select2 it is fire multiple times. Ex. if i have three rows and If i will change first select2 controls item then in console it showing same value but three times. How can i prevent this?

As we know this is a dynamic table with control, How can i display Ledger balance accordingly to their balance input-text?

Take a look in jsfiddler


Solution

  • I am answering your query, considering you are using table tags.

    $(document).on('change', '.select2_el', function(event) {
        let selected_value = $(this).val()
        // it get goes to your <tr> tag
        let tr = $(this).closest('tr');
        
        // it will find inside your balance input-box and set the value.
        tr.find('input[name="balance[]"]').val(selected_value);
    });
    

    Hope this will save your time!!

    Happy Coding!!! 🚀