truckingsim / Ajax-Bootstrap-Select

This uses the bootstrap-select plugin and extends it so that you can use a remote source to search.
MIT License
280 stars 97 forks source link

Attempting to destroy selectpicker and reinitialize ajaxselect creates standard select #196

Open coreynbryant opened 4 years ago

coreynbryant commented 4 years ago

I was hoping someone could point me in the right direction here. I am using two different selectpickers. The first select changes values in my ajaxselect selctpicker. It is working fine but I noticed that because I am using the cache from ajax select it is possible to get incorrect data to the user.

I am attempting to destroy the selectpicker and then reinit it when the first select is changes.bs.select but my ajax select never comes back and it just stays as a standard bootstrap select.

    var $selectOne = $('#selectOne');
    var $selectTwo = $('#selectTwo');
    var options = {
        ajax: {
            url: 'ajax',
            type: "GET",
            dataType: "json",
            contentType: 'json',
            data: function () {
                var params = {
                    term: '{{{q}}}'                       
                };

                params.changedValue = parseInt($('#selectOne').val()) > 0 ? parseInt($('#selectOne').val()) : null;

                return params;
            }
        },
        locale: {
            searchPlaceholder: 'Search for stuff...',
            statusInitialized: 'Start typing to begin search'
        },
        clearOnEmpty: false,
        log: 4,
        minLength: 2,
        requestDelay: 500,
        preserveSelected: false
    };

    $selectOne.on('changed.bs.select', function () {
        $selectTwo.selectpicker('destroy');
        $selectTwo.selectpicker({ liveSearch: true }).ajaxSelectPicker(options);
    });
ourcoteam commented 3 years ago

Same here

truckingsim commented 3 years ago

@coreynbryant yeah we don't really support that out of the box. The thing Ajax-Bootstrap-Select is looking for on initialize is the jquery data property AjaxBootstrapSelect. If you do:

$selectOne.on('changed.bs.select', function () {
        $selectTwo.selectpicker('destroy');
        $selectTow.removeData('AjaxBootstrapSelect');
        $selectTwo.selectpicker({ liveSearch: true }).ajaxSelectPicker(options);
    });

instead it should let Ajax-Bootstrap-Select go through its normal init. I'm not sure to be honest if this will have other side effects but it should force the re-init.