Reputation:
I'm using the following jQuery function to populate a dropdown list. Once the user selects an item I am storing the selected value in a session variable and Im able to get the data back from the session variable via a hidden filed in to a variable (selectedApp) after a postback.
The problem is that after a postback I am not able to set the list back to the selected item that teh use selected before clicking submit.
How can I set the selected item in the drop down list to be the selected item?
var selectedApp = $('#selectedApplication').val();
$.getJSON("/ApplicationSettings/Applications/List", function(data) {
var items = "<option>----------- Select Application to Configure ----------</option>";
$.each(data, function(i, application) {
items += "<option value='" + application.Value + "'>" + application.Text + "</option>";
});
$("#Applications").html(items);
});
Upvotes: 0
Views: 2060
Reputation:
Thanks!
This is what i ended up doing.
$.getJSON("/ApplicationSettings/Applications/List", function(data) {
var items = "<option>----------- Select Application to Configure ----------</option>";
$.each(data, function(i, application) {
var selected = (application.Value == selectedApp) ? 'selected' : '';
items += "<option value='" + application.Value + "'" + selected + ">" + application.Text + "</option>";
});
$("#Applications").html(items);
});
Upvotes: 0
Reputation: 105888
Have your ajax endpoint return each option's selected state? Because unless I'm missing something, at this point the server should be aware of which option was selected
Right now, it seems your JSON looks like this
[
{"Value": 1, "Text": "One"}
, {"Value": 2, "Text": "two"}
// etc
]
Just modify it to this
[
{"Value": 1, "Text": "One", "Selected": false}
, {"Value": 2, "Text": "two", "Selected": true}
// etc
]
And make your callback use the value appropriately
$.each(data, function(i, application) {
var selected = application.Selected? ' selected' : '';
items += "<option value='" + application.Value + "'" + selected + ">" + application.Text + "</option>";
});
Upvotes: 0
Reputation: 37267
You can change the inside of your each
to be:
items += "<option value='" + application.Value + "' " + (selectedApp === application.Text ? "selected" : "" ) + ">" + application.Text + "</option>";
Assuming selecteApp
holds the text value. Otherwise use application.Value
to compare.
Upvotes: 1