jqueryjquery-ui-multiselect

How to reload jQuery multiselect in a drowdown list when the selection of another dropdown changes


I have tried some of the solutions proposed in this forum but they did not work for so I think I am missing something somewhere.

I am using Patrick Springstubbe jQuery multiselect on two dropdown lists(ProductCategories and Products).

I want the list of products to change depending on what's selected in the ProductCategories multiselect.

The code I am using for that is as follows:-

	$("#ProductCategory").change(

		function () {

		$("#leftlist").empty();

		$("#ProductCategory").children("option:selected").each(function () {

			ResetLeftList(($(this).val()));		

		});
		
		$('#leftlist').multiselect( 'reload' );

	});

function ResetLeftList(ProductCategoryID) {

  //Get list of food for categoryID

  $.ajax

  ({

    url: "http://example.com/index.php?id=18",
    data: {
      PostProductCategoryID: ProductCategoryID
    },
    method: "post",
    success: function(result) {

      var trimmedresult = result.substring(3, result.length - 4);
      var newOptions = trimmedresult.split(";");

      for (i = 0; i < newOptions.length; i++) {

        var option = newOptions[i].split(",");

        $("#leftlist").append($("<option></option>").attr("value", option[0]).text(option[1]));

      }

    }

  });


}

Problem:- The product multiselect don't update

Observation:- Using developer tool on the web browser I can see that the list of options in the product list is changing as expected. If I remove $("#leftlist").empty(); the product multilist updates based on the previously selected options from the category list. It appears that $('#leftlist').multiselect( 'reload' ) is firing before the option changes in the product list.


Solution

  • You are right "$('#leftlist').multiselect( 'reload' ) is firing before the option changes in the product list.".

    jQuery.ajax performs an asynchronous HTTP (Ajax) request.

    which means that code will continue executing after $.ajax() is called.

    You can use the jqXHR Object returned by $.ajax() and place the reload code in a callback that will be executed when the request is finished.

    Return the jqXHR Object:

    function ResetLeftList(ProductCategoryID) {
        return $.ajax
    

    Wait for all ajax to finish

     var requests = new Array();
    
     $("#ProductCategory").children("option:selected").each(function () {
    
         requests.push(ResetLeftList(($(this).val())));     
    
     });
    
     $.when.apply($, requests).done(function( x ) {
         $('#leftlist').multiselect( 'reload' );
     });