MahmoudAdelAli's avatar

Bootstrap Select Not Working With Dynamic Data Ajax

Hi , i have ajax fetch data as json but when i use it with bootstrap select it doesn't work , even after i refresh it cause the select box is disappearing

    let mySelect = $('.cities'),
        countrySelect = $('.countries');
      countrySelect.change(function () {
        mySelect.selectpicker('refresh');
        $.getJSON("{{route('clients.cities',)}}/" + $(this).val(), function (data) {
          mySelect.empty();
          $.each(data, function (index, item) {
            mySelect.append($('<option>').text(item).val(item));

          });
          mySelect.selectpicker('refresh');
        });

      });
0 likes
4 replies
LaryAI's avatar
Level 58

It looks like you are missing a few steps in your code. You need to add the refresh method after you have appended the new options to the select box. Try the following code:

let mySelect = $('.cities'),
    countrySelect = $('.countries');
  countrySelect.change(function () {
    mySelect.selectpicker('refresh');
    $.getJSON("{{route('clients.cities',)}}/" + $(this).val(), function (data) {
      mySelect.empty();
      $.each(data, function (index, item) {
        mySelect.append($('<option>').text(item).val(item));
      });
      mySelect.selectpicker('refresh'); // Add this line
    });
  });

This should ensure that the select box is refreshed after the new options have been added.

MahmoudAdelAli's avatar

@LaryAI sorry i missing that , i added it before but it doesn't work too , and i take the code copy when i deleted it , it visible like div with ul without my select box .

MahmoudAdelAli's avatar

@LaryAI also

            mySelect.selectpicker('refresh').empty().append($('<option>').text(item).val(item)).selectpicker('refresh').trigger('change');

not work too

MahmoudAdelAli's avatar
MahmoudAdelAli
OP
Best Answer
Level 5

It works after i change the myselect from class select to id :)

  let mySelect = $('.cities'),  //From
let mySelect = $('#region'),  // To

Please or to participate in this conversation.