如何动态更改下拉列表值

时间:2017-11-21 07:55:58

标签: javascript jquery

我正在使用davidstutz bootstrap-multiselect插件,我想根据客户端下拉值更新部门下拉列表的值

以下是Client Dropdown(C#ASP.Net Format)的代码

@Html.DropDownList("ClientID", null, "Select Client", new { @class = "form-control",@required="required" })

部门下拉代码

<select id="Agents[0].Departments" name="Agents[0].Departments" class="form-control AgentDepartments" multiple>
                                            </select>

最初我正在应用插件并在客户端更改时我正在重新分配插件,但它没有更新部门下拉值

Jquery代码

$(function () {   
  $('.AgentDepartments').multiselect({
    includeSelectAllOption: true,
    height: '20px'
  });

  $("#ClientID").on('change',function () {
    var CIN = $('option:selected', this).text();

    $.ajax({
      type: "get",
      url: '/Client/GetDepartmentList',
      contentType: "application/json; charset=utf-8",
      data: { "CIN": CIN },
      datatype: "json",
      success: function (data) {
        $('.AgentDepartments').empty();
        $.each(data, function () {
          $(".AgentDepartments").append($("<option/>").val(this.KeyName).text(this.ValueName));
        });

        $('.AgentDepartments').multiselect({
          includeSelectAllOption: true,
          height: '20px'
        });
      },

      error: function () {
        alert("Failed to load Data.");
        toastr.warning('Something went wrong!', null, { "closeButton": true });
      },

      beforeSend: function () {
        $('#loadingDiv').show();
      },

      complete: function () {}
    });
  });
});

2 个答案:

答案 0 :(得分:0)

我认为,首先需要在更改/附加选项后销毁然后重新初始化:

$(".AgentDepartments").append(toAppend).multiselect("destroy").multiselect();

或者,我想,你也可以:

$(".AgentDepartments").append(toAppend).multiselect('refresh');

答案 1 :(得分:0)

而不是这样做

$('.AgentDepartments').multiselect({
   includeSelectAllOption: true,
    height: '20px'
});

尝试重建下拉列表

$('.AgentDepartments').multiselect('rebuild')