operator
operator

Reputation: 257

Bootstrap select dropdown made dynamic?

Here's my static HTML:

<select name="codici_transazioni" class="selectpicker" id="codici_transazioni">
    <option value="dsjkcbs">dsjkcbs - <i>Email, Facebook</i></option>
    <option value="scgwfsd" selected class="normaleSelect">scgwfsd - <i>Facebook</i></option>
    <option value="stdstyd">stdstyd - <i>Twitter</i></option>
</select>

This is a piece of code taken from a modal context. I want my select to be filled with the result of an Ajax performed on a .php file that returns results from my MySQL DB.

Now, all the Ajax and DB parts are working, what is not is that when I try to fill this <select> via jQuery after the Ajax has succeeded, the result is the same as the default above!

Here's my jQuery:

$('#codici_transazioni').html("");
for (var i = received.length - 1; i >= 0; i--) {
    <other DOM loading>
     $('#codici_transazioni').append("<option value=" + temp_code_transaction + "> " + temp_code_transaction + "- <i>" + temp_type_transaction+ "</i></option>");
}

I noticed via Chrome (so after the loading of the page) that some div has been created after the select.

enter image description here

I know this is done by Bootstrap, but how can I reload the creation of this code after the Ajax has performed to make the select dropdown dynamic?

Upvotes: 1

Views: 10124

Answers (2)

Franco
Franco

Reputation: 2329

Use ajax:

$('#codici_transazioni').html('')
         $.ajax({
             url: '/path/to/phpfile',
             type: 'POST',
             dataType: 'json',
         })
         .done(function(data) {
             var output = '';
            $.each(data,function(index, el) {
                output += '<option class="results" value="'+el.valueToPass+'">'+el.valueToPass+'</option>'+

            });
            $('#codici_transazioni').append(output)
         })
         .fail(function() {
             console.log("error");
         })

I can not be more pecific because you didn't post the php file and you don't say in which way you want trigger the result.

NOTE: It will be better if you will give to your existing options a class of 'results' or whatever you like, so you can clean the existing options before you load the new one.

In place to use:

$('#codici_transazioni').html('')

You can do:

$('.results').remove()

Upvotes: 0

Synapse
Synapse

Reputation: 901

If you are using bootsrap-select you should also run the refresh() method after you appended the new options to the select

.done(function(data){
    'appending process'...
    $('#codici_transazioni').selectpicker('refresh');
})

Upvotes: 6

Related Questions