Home > database >  append option to select - jquery
append option to select - jquery

Time:10-23

i use jquery to append options to select with these classes and id But when I use this class (form-control selectpicker ), my code does not work

select element :

<select class="form-control selectpicker" data-live-search="true" id="lessonsDD">
</select>

jquery Ajax :

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "/LinksManager/GetLessons",
    dataType: "json",
    success: function(res) {
      //console.log(res);
      $.each(res, function(index, value) {
        $("#lessonsDD").append('<option value='   value.id   '>'   value.lessonName   '</option>');
      });
    }
  });
});

But it works when I delete the class!!

how can i fix it ?

CodePudding user response:

<select class="form-control selectpicker" data-live-search="true" id="lessonsDD">
</select>

The issue related the selectpicker class. From the above code, I assume you are using the bootstrap-select package, right?

From the bootstrap-select official document, we can see that add the selectpicker class to the select elements, it will auto-initialize bootstrap-select.

enter image description here

Since the select element's options is dynamically added, after adding the select options, you should use the JavaScript method to call the bootstrap-select.

So, please modify your code as below:

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "/LinksManager/GetLessons",
    dataType: "json",
    success: function(res) {
      //console.log(res);
      $.each(res, function(index, value) {
        $("#lessonsDD").append('<option value='   value.id   '>'   value.lessonName   '</option>');
      });
      $('#lessonsDD').selectpicker();
    }
  });
});

The result as below (test it in an Asp.net 5 application):

enter image description here

  • Related