Home > Software design >  TomSelect - refresh options in dependent Dropdown after repeated ajax load
TomSelect - refresh options in dependent Dropdown after repeated ajax load

Time:09-29

Im using enter image description here

The <option>...</option> list of the To dropdown depends on the From dropdown and is updated per ajax call on the selection in the From dropdown. The first initialization works fine on both dropdowns. Unfortunately, after repeating the ajax request through selecting another location on the From dropdown results in the following error:

Uncaught Error: Tom Select already initialized on this element 

What i did so far:

1. On page load i'm initializing TomSelect on the From dropdown with:

tsfrom = new TomSelect('#from-select-field',ttddssettings);

enter image description here

The relevant lines of code:

    <select id="from-select-field" name="from" onchange="getTo();">  
    <option value='0'>Choose...</option>
    </select>

    <select id="to-select-field" name="from">  
        <option value='0'>Select From first</option>
    </select>

    <script>

        jQuery(document).ready(function($) {
            
            var tsfrom;     
            var ttddssettings = {   
                plugins: ['dropdown_input'],
            };
            tsfrom = new TomSelect('#from-select-field',ttddssettings);
            
            var totoval = "xymydomain.com/get-to-options.php";              
            getTo = function () {

                var fromvalue = $("#from-select-field").val();
                var tovalue = $("#to-select-field").val();
            
                $.ajax({
                    type: "POST",
                    url: totoval,           
                    data: {
                        from: fromvalue,
                        to: tovalue,                                
                    },                                          
                    success: function(data) {
                        $("#to-select-field").html(data);
                    },                      
                });
            }

        });

    </script>

The relevant lines of code inside the requested PHP file:

    <?php               
        $sql_to = "SELECT * FROM locations WHERE ..... ORDER by names ASC";                     

        $quer_to = $pdo_conn->prepare($sql_to);
        $quer_to->execute();
        $fetch_to_values = $quer_to->fetchAll();                                        
        
        foreach ( $fetch_to_values as $tovalues ) {
    ?>
        <option value="<?php echo $tovalue['name']; ?>" <?php if ( $tovalue['name'] == $to) { echo "selected";} ?>><?php echo $tovalue['name']; ?></option>                                 
    
    <?php } ?>

    <script>

        jQuery(document).ready(function($) {
            
            var tsto;       
            var tttossettings = {   
                plugins: ['dropdown_input'],
            };
            tsto = new TomSelect('#to-select-field',tttossettings);

        });

    </script>

2. After selcting a From location the To dropdown gets populated per ajax. The requested file (see above) through ajax url: includes also the following code to initialize TomSelect on the To dropdown:

tsto = new TomSelect('#to-select-field',tttossettings);

enter image description here

So far everything works fine.

3. THE PROBLEM:

As mentioned before, after repeatedly selecting a different location on the From dropdown i get the error Tom Select already initialized on this element.

The TomSelect DOCS mentioning refreshOptions(triggerDropdown) (Refreshes the list of available options shown in the autocomplete dropdown menu.). Unfortunately I have no idea if this is the right approach or how to fix this. Any help would be greatly appreciated.

CodePudding user response:

Two changes should get rid of the error:

Remove script block from PHP page:

Get rid of the <script> block in your PHP file and only return the <option>...</option> values. This is also messy as you are setting the HTML of the <select> to be what the PHP code has generated, including the returned script block.

Trigger updating the drop down in the AJAX success block

$.ajax({
    type: "POST",
    url: totoval,           
    data: {
        from: fromvalue,
        to: tovalue,                                
    },                                          
    success: function(data) {
        $("#to-select-field").html(data);
        tsto.clear(); // unselect previously selected elements
        tsto.clearOptions(); // remove existing options
        tsto.sync(); // synchronise with the underlying SELECT
    },                      
});

Using the sync method should update the styled dropdown options based on the underlying <select>.

Alternatively, calling tsfrom.refreshOptions(); instead of sync() could also work.

  • Related