Reputation: 271
I am trying to bind selected option as dropdown selected value in jquery. I am doing it after binding dropdown options via json. After the form submit i am unable to select the dropdown options.
Binding Dropdown Options:
$.getJSON('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]/Home/GetLanguages', function (authors) {
$.each(authors, function (index, author) {
$('#ddlLanguages').append(
$('<option/>')
.attr('value', author.LanguageKey)
.text(author.LanguageKey)
);
});
});
jquery to set the value
$('select[name^="Languages"] option[value='+name+']').attr("selected", "selected");
How this can be done.. can anyone help me on this?
Upvotes: 0
Views: 71
Reputation: 271
I found a solution for this. Instead of setting the dropdown value after binding the options, we can do it while binding the options.
Here is the solution.
$.getJSON('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]/Home/GetLanguages', function (authors) {
$.each(authors, function (index, author) {
if ('@SelLang' == author.LanguageKey)
{
$('#ddlLanguages').append(
$('<option/>')
.attr('value', author.LanguageKey).attr('selected','selected')
.text(author.LanguageKey)
);
}
else{
$('#ddlLanguages').append(
$('<option/>')
.attr('value', author.LanguageKey)
.text(author.LanguageKey)
);
}
});
});
Here @SelLang is the dropdown value after submitting the form.
Upvotes: 1
Reputation: 1749
Couldn’t you simply set the value of the select?
Something like
$('select[name^="Languages"]).val(name);
You can also get your select like this
$("[name='Languages']").val(name);
And I am assuming you get the data and when it is done you set the value. If you just execute the get for the data and immediately execute the set the data might not be loaded before you try to set the value.
Tried to add this as comment but on mobile app it only allows me 15 characters?
Upvotes: 0