Home > DeveloperSection > Forums > How to assign hiddenfield value to select2 on postback
Ashish Pandey

Total Post:128

Points:898
Posted on    January-26-2015 10:49 PM

 C# ASP.Net  JQuery 
Ratings:


 1 Reply(s)
 2786  View(s)
Rate this:

I am trying to assign value to select2 control from a hiddenfield in clientside script. Value is not assigned to select2 control after postback for the following code.

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

 

});

However value get assigned if I put alert before assigning

var SelectedIndustry = $('#HiddenIndustrySectorID').val();

 

alert(SelectedIndustry);

 

$("#cboIndustry").select2().select('val',SelectedIndustry);

 

// These steps I have included, for retaining value in select2 on postback.

What could be the reason? Please help me.



Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    January-27-2015 12:17 AM

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

        }

    });

 });


Don't want to miss updates? Please click the below button!

Follow MindStick