HOW TO ASSIGN HIDDENFIELD VALUE TO SELECT2 ON POSTBACK

Ashish Pandey

Total Post:128

Points:898
Posted by  Ashish Pandey
C#
 3754  View(s)
Ratings:
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.

  1. Manoj Bhatt

    Post:154

    Points:1086
    Re: How to assign hiddenfield value to select2 on postback

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

            }

        });

     });

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!