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