当另一个下拉列表的选择发生变化时,如何在下拉列表中重新加载 jQuery 多选

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

我已经尝试了这个论坛中提出的一些解决方案,但它们没有用,所以我想我在某处遗漏了一些东西。

我在两个下拉列表(ProductCategories 和 Products)上使用 Patrick Springstubbe jQuery 多选。

我希望根据在 ProductCategories 多选中选择的内容更改产品列表。

我为此使用的代码如下:-

 $("#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]));

      }

    }

  });


}

问题:- 产品多选不更新

观察:- 在 Web 浏览器上使用开发人员工具,我可以看到产品列表中的选项列表正在按预期更改。 如果我删除 $("#leftlist").empty();,产品多列表会根据先前从类别列表中选择的选项进行更新。 似乎 $('#leftlist').multiselect( 'reload' ) 在产品列表中的选项更改之前触发。

你是对的“$('#leftlist').multiselect( 'reload' ) 在产品列表中的选项更改之前触发。”。

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

这意味着代码将在 $.ajax() 被调用后继续执行。

您可以使用 jqXHR Object returned by $.ajax() 并将重新加载代码放在请求完成时将执行的回调中。

Return jqXHR 对象:

function ResetLeftList(ProductCategoryID) {
    return $.ajax

等待所有 ajax 完成

 var requests = new Array();

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

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

 });

 $.when.apply($, requests).done(function( x ) {
     $('#leftlist').multiselect( 'reload' );
 });