加载值后更改下拉菜单的值

本文关键字:下拉菜单 加载 | 更新日期: 2023-09-27 17:54:59

我需要在加载其中的所有值后设置dropdown值。第一个dropdown (District)值加载第二个dropdown (Councils)的值,JSon调用使ID选择Councils dropdown中的值,但必须在完全加载后才能设置:

$("#PostalCode").keyup(function () {
    loadPTPostalCode();
});
$("#PostalCodeExtension").keyup(function () {
    loadPTPostalCode();
});
function loadPTPostalCode()
{
    if ($("#PostalCode").val() >= 1000) {
       $.ajax({
            url: '/Address/GetPTPostalCode',
            type: "POST",
            dataType: "json",
            data: { postalCode: $("#PostalCode").val(), postalCodeExtension: $("#PostalCodeExtension").val() },
            success: function (data) {
                 //Set the Distict value and fire the load of the Councils Dropdown
                $("#districtDropdown").val(data.PTCouncil.PTDistrict.Id).change(function () {
                 // I tried to define the Council value after the load of his dropdown changes but no luck
                    $("#councilDropdown").val(data.PTCouncil.Id);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert(textStatus)
            }
        });
    }
}
编辑:

我还有一个与District下拉列表相关联的级联:

$("#districtDropdown").cascade({
    url: "/Address/ListCouncilByDistrict",
    paramName: "districtId",
    firstOption: 'Selecione o Concelho...',
    childSelect: $("#councilDropdown")
});

加载值后更改下拉菜单的值

我不确定我完全理解你的问题,但试试这个:

 success: function (data) {
                 //Set the Distict value and fire the load of the Councils Dropdown
                $("#districtDropdown").val(data.PTCouncil.PTDistrict.Id).change(function () {
                 // I tried to define the Council value after the load of his dropdown changes but no luck
                    $("#councilDropdown").val(data.PTCouncil.Id);
                }).change();
            }

您必须在council下拉列表中设置值,只有在它被加载之后,这可能通过另一个Ajax调用发生。我假设您有另一个java脚本代码,该代码正在加载区域值更改时的理事会值(可能在区域下拉的更改处理程序中)。所以你需要在这个函数中设置理事会值。大纲应该是这样的

success: function (data) {
  //Set the Distict value
  $("#districtDropdown").val(data.PTCouncil.PTDistrict.Id);
  // store the council id in temp storage (currently using DOM element)
  $("#councilDropdown")[0]["temp_council_id"] = data.PTCouncil.Id;
  // fire loading of council drop-down
  $("#districtDropdown").change(); // this is assuming that change handler has the
                                   // relevant code. If not then invoke that code.
}
现在,在加载council下拉列表的代码中,添加代码从临时存储 中设置council id
$("#districtDropdown").change(function() {
   // code to load council drop-down
   ....
   // set the selected council id (if any)
   var councilId = $("#councilDropdown")[0]["temp_council_id"];
   if (councilId) {
       $("#councilDropdown").val(councilId);
       $("#councilDropdown")[0]["temp_council_id"] = null; // clear temp storage
   }
});