最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TomSelect - refresh options in dependent Dropdown after repeated ajax load - Stack Overflow

programmeradmin1浏览0评论

Im using TomSelect to control my <select> UI for my dependent select dropdowns.

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);

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/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);

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 autoplete dropdown menu.). Unfortunately I have no idea if this is the right approach or how to fix this. Any help would be greatly appreciated.

Im using TomSelect to control my <select> UI for my dependent select dropdowns.

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);

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./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);

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 autoplete dropdown menu.). Unfortunately I have no idea if this is the right approach or how to fix this. Any help would be greatly appreciated.

Share Improve this question asked Sep 29, 2022 at 5:29 evaviennaevavienna 1,11916 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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.

ChatGPT remended this to me:

const selectElement = document.querySelector('select');

// Check if Tom Select has already been initialized
if (!selectElement.tomselect) {
  new TomSelect(selectElement);
}

Only thing it missed is that selectElement.tomselect attribute is written with small "s". Eg: not tomSelect but tomselect

See: https://github./orchidjs/tom-select/blob/69180fa9e79060060f1824fbde85537579d0005d/src/tom-select.ts#L103

发布评论

评论列表(0)

  1. 暂无评论