Bootstrap multiselect refresh or rebuild does not work

user1688401 picture user1688401 · Jun 20, 2016 · Viewed 7.4k times · Source

I want to bind my multiselect with ajax but after ajax call items does not show.I try rebuild or refresh multiselect but it still does not show

 <script type="text/javascript">
     $(document).ready(function () {

         var categCheck = $('#multiselect').multiselect({
             includeSelectAllOption: true,
             enableFiltering: true
         });


         $.ajax({
             type: 'GET',
             url: "@Url.Content("~/Home/Listpositions/")",
             success: function (data) {
                 $.each(data.data, function (index, item) {
                     alert(item.PositionName);
                     var opt = $('<option />', {
                         value: item.PID,
                         text: item.PositionName
                     });
                     opt.appendTo(categCheck);

                 });
             }
         });
         $('#multiselect').multiselect('rebuild');
         categCheck.multiselect('rebuild');

         categCheck.multiselect('refresh');
         $("select.multiselect").multiselect("refresh");
   });
        </script>

Here is my multiSelect page link:http://pratikisara.com/Home/Quick This is multiselect but it is empty

How can I make ajax call from multiselect JS file(enter link description here) and in which code block should I do ajax call?

Answer

David Stutz picture David Stutz · Sep 2, 2016

You need to to the rebuild and/or refresh in the AJAX success function. In your code, the AJAX call is made, then the multiselect is rebuild. But the rebuilt may happen before the AJAX call succeeds. Try this:

<script type="text/javascript">
   $(document).ready(function () {

     var categCheck = $('#multiselect').multiselect({
         includeSelectAllOption: true,
         enableFiltering: true
     });


     $.ajax({
         type: 'GET',
         url: "@Url.Content("~/Home/Listpositions/")",
         success: function (data) {
             $.each(data.data, function (index, item) {
                 alert(item.PositionName);
                 var opt = $('<option />', {
                     value: item.PID,
                     text: item.PositionName
                 });
                 opt.appendTo(categCheck);

                 // Rebuild after adding the options!
                 $('#multiselect').multiselect('rebuild');
             });
         }
     });
  });
</script>