window.addEventListener('load', function() { $('#transport-provider-id').select2({ placeholder: 'Search by Transport Provider name', maximumSelectionSize: 1, ajax: { url: '/Transport_provider_accounts/getTransportProviderByName', type: 'GET', dataType: 'json', delay: 250, processResults: function (res) { return { results: jQuery.map(res.data, function(item) { return { id: item.id, text: item.name } }) }; }, cache: true }, }); // Everytime the search box changed, will update the value of hidden field $('#transport-provider-id').on('change', () => { $("#transport-provider-name").val($(".select2-selection__rendered").text()); }); // Set text default for Transport Provider Name $(".select2-selection__rendered").text($("#transport-provider-name").val()); const data = { id: $('#transport-provider-id-hidden').val(), text: $('#transport-provider-name').val() }; var newOption = new Option(data.text, data.id, false, false); $('#transport-provider-id').append(newOption).trigger('change'); });