Bootstrap-Select refresh works randomly

Viewed 688

Now I know this question has been asked quite a bit, but I cannot seem to make the bootstrap-select refresh properly after adding values to my select dynamically.

I'm using bootstrap-select 1.13.14. Once my page is loaded, it calls this loadFunctionTitles() function that'll 1) empty my select box choices; and then 2) append proper options from a JS array...

Visual is essentially this :

enter image description here

When I click on either of the function types, or even click on my delete icon to clear the selected value, the select list box refreshes no problems. However, when my page loads, I get random "refreshes". My selected value when looking into inspect mode always shows me the right value, but for some reason, the refresh doesn't seem to always work! It almost seems random : sometimes it'll properly choose my given value, sometimes not...

My JS code :

// pre-load function titles
$(document).ready(function(){
    loadFunctionTitles( funcTypeID, funcPreSelTitleID );
});

/**
 * loadFunctionTitles()
 * Loads function titles based on type id (Artistic, Technical, etc.)
 * @param int typeid load function titles for given type id
 * @param int preSelId pre-select list value
 */
function loadFunctionTitles(typeid, preSelId) {

    $('#function_title_id').empty();

    if( typeof functionTitles[typeid] != 'undefined' ) {

        $( '#function_title_id' ).prop( "disabled", false );

        functionTitles[typeid].forEach(function(funcTitle) { 
            $('#function_title_id').append('<option value="' + funcTitle.id + '"' + (funcTitle.id == preSelId ? ' selected' : '') + '>' + localejs._d('function_titles', funcTitle.name ) + '</option>');
        });
    }

    // disable function titles dropdown if we don't have any
    else {
        $( '#function_title_id' ).prop( "disabled", true );
    }

    // force refresh of bootstrap-select!
    if($('#function_title_id').selectpicker) {
        $('#function_title_id').selectpicker('refresh');
    }
}

And my HTML :

<select name="function_title_id" 
id="function_title_id"  
title="Please select..."                        
class="form-control selectpicker" 
data-live-search="true"
disabled>
</select>

I don't understand what I am doing wrong. I've seen mentions of the need to re-add the 'selectpicker' class before doing the refresh, and many other things I've read, but nothing is working on for me.

Any help would be great! Thanks a million!! Pat

UPDATE: I've added a fiddle with a working copy of what I have so far. Changing the radio option refreshes the lists, but will not preselect my desired value...

https://jsfiddle.net/hd41mojx/

0 Answers
Related