回发时无法将hiddenfield值分配给select2

本文关键字:分配 select2 hiddenfield | 更新日期: 2023-09-27 18:10:20

我正试图从客户端脚本中的隐藏字段中为select2控件赋值。以下代码回发后,未将值分配给select2控件。

$(document).ready(function () {
     $("#cboIndustry").select2();
     $.getJSON(uriSector+ '/' + 'GetIndustrySectors')
           .done(function (data) {
               $.each(data, function (key, item) {
                  $("#cboIndustry").append($("<option></option>").val(item.IndustrySectorID).html(item.IndustrySectorName));
               });
           });
     $("#cboIndustry").on('change', function () {
            if ($("#cboIndustry").val() != "-1") {
                 var id = $("#cboIndustry").val();
                $('#HiddenIndustrySectorID').val(id);
                SelectedName = $('#cboIndustry option:selected').text();
                $('#HiddenIndustrySectorName').val(SelectedName);
            }
        });
   var SelectedIndustry = $('#HiddenIndustrySectorID').val();
   $("#cboIndustry").select2().select('val',SelectedIndustry);
});

但是,如果我在分配之前发出警报,则会分配值

var SelectedIndustry = $('#HiddenIndustrySectorID').val(); 
alert(SelectedIndustry);
$("#cboIndustry").select2().select('val',SelectedIndustry); 
// These steps I have included, for retaining value in select2 on postback.

原因可能是什么?请帮帮我。

回发时无法将hiddenfield值分配给select2

为什么不使用这行

$("#cboIndustry").select2().val(SelectedIndustry); 

BTW我没有测试

 $('#HiddenIndustrySectorID').val(id);

将此行更改为

document.getElementById("HiddenIndustrySectorID").value =id;

并尝试

$(document).ready(function () {
    $("#cboIndustry").select2();
    $.getJSON(uriSector+ '/' + 'GetIndustrySectors')
       .done(function (data) {
           $.each(data, function (key, item) {
              $("#cboIndustry").append($("<option></option>").val(item.IndustrySectorID).html(item.IndustrySectorName));
        });
    //This change solves my problem
    var SelectedIndustry = $('#HiddenIndustrySectorID').val();
    $("#cboIndustry").select2().select('val',SelectedIndustry);
 });
 $("#cboIndustry").on('change', function () {
        if ($("#cboIndustry").val() != "-1") {
            var id = $("#cboIndustry").val();
            $('#HiddenIndustrySectorID').val(id);
            SelectedName = $('#cboIndustry option:selected').text();
            $('#HiddenIndustrySectorName').val(SelectedName);
        }
    });
 });