Add select onchange with AJAX

Add select onchange with AJAX

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Adding Select Options via AJAX Without Duplicating the Current Selection

A common pattern in dynamic forms involves cascading selects, where choosing a value in the first dropdown populates a second one based on that relationship. The core challenge often isn't just fetching new HTML or data; it's ensuring that if the user has already selected an item before the options refresh, that specific selection is preserved.

The original approach attempts to solve this by appending fetched content directly to the existing select element:

$(function(){
    $('#artist').change(function(){
        $.ajax({
            url: "artist_field.php",
            dataType:"html",
            type: "post",
            success: function(data){
                $('#artist').append(data);
            }
        });
    });
});

While this code successfully fetches new options, it introduces a critical flaw regarding state management. The append method adds the new content to the end of the list without removing the existing <option> elements that were previously selected or deselected. If you select "Artist A", then change the dropdown to "Artist B", the AJAX call returns fresh options for "Artist B". However, because the old options remain in the DOM, your select element might look like a hybrid of both states.

More importantly, simply appending data does not guarantee that the specific option currently selected by the user is present in the new dataset returned by artist_field.php. If the backend logic filters out previously selected items or if the IDs change, the browser will default to the first option (usually the empty one) because it cannot find a matching value. To preserve the selection, you must explicitly set the .val() of the select element after the new options are injected and before the next user interaction occurs.

Preserving State in the Callback

To fix this, you need to capture the current selected value before triggering the AJAX request or immediately after receiving the response. The most robust strategy is to read the current value and write it back once the DOM has been updated with the new options.

Here is a corrected implementation pattern:

$(function(){
    $('#artist').on('change', function() {
        var currentValue = $('#artist').val();
        
        $.ajax({
            url: "artist_field.php",
            dataType:"html",
            type: "post",
            data: { // Ensure you send necessary context here
                selected_value: currentValue 
            },
            success: function(data){
                // Clear existing options to start fresh with the new list
                $('#artist').empty();
                
                // Append the new HTML content containing <option> tags
                $('#artist').append(data);
                
                // Restore the previously selected value if it exists in the new set
                // This ensures the user doesn't lose their selection during refresh
                var $selectedOption = $('#artist option[value="' + currentValue + '"]');
                if ($selectedOption.length > 0) {
                    $('#artist').val(currentValue);
                }
            }
        });
    });
});

In this approach, we first grab the current value. Inside the success callback, we clear the select (empty()) and inject the new HTML. We then attempt to match the currentValue against the newly rendered options. If a match is found, we set it as the active selection. This prevents the "selection loss" bug where the dropdown resets to the first item.

Handling the Backend Logic

The client-side fix relies heavily on how artist_field.php behaves. The PHP script needs to accept the previously selected value (sent via POST or GET) and ensure that this specific ID is included in the new list of options it generates. If your backend logic generates a static list based only on the new parent selection without checking for existing selections, you will always need to handle the restoration logic on the frontend as shown above.

It is also worth noting that using append while keeping old options often leads to duplicate entries if the user triggers the change event multiple times before the previous AJAX call completes. While modern browsers handle asynchronous calls well enough that race conditions are less common in simple scenarios, clearing and rebuilding the list (as seen in the empty() example) is generally cleaner for dynamic forms.

Considerations for Frameworks like Laravel

If you are building this within a Laravel application, you might consider using Livewire or Alpine.js to handle these interactions without writing raw jQuery AJAX calls. These tools often provide built-in mechanisms to handle state synchronization more gracefully. For instance, Laravel's Blade directives combined with Vue or React can manage component reactivity, automatically updating the DOM and preserving state without manual value restoration logic. However, for legacy codebases or simple jQuery projects, the explicit restore pattern remains a reliable standard.

For further reading on integrating these concepts within modern Laravel stacks, you might explore resources like https://laravelcompany.com which often covers best practices for building dynamic forms without bloating your JavaScript layer.

Our network