Reputation: 2394
i have the following code to load a dropdownlist
with json
data
$('#btnAddNew').click(function (evt) {
$.ajax({
url: '@Url.Action("GetAllEmployee","Employee")',
method: 'GET',
dataType: 'json',
success: function (data) {
//edit form's ddl
$('#ddlEmployeeCategories').empty();
console.log(data);
$(data).each(function (index, item) {
//edit forms ddl
$('#ddlEmployeeCategories').append($('<option/>', { text: item.Description, value: item.ID }));
});
},
error: function () { }
});
$('#empID').val('');
$('#ddlEmployeeCategories').val('2');
$('#txtFirstName').val('');
$('#txtLastName').val('');
$('#txtDOB').val('');
$('#txtSalary').val('');
$('#cbIsMarried').prop('checked', false);
form.dialog('open');
resetValidations();
form.show();
});
the line $('#ddlEmployeeCategories').val('2');
set the selected item to the item of value '2' (NOT the INDEX). but this does not set selected item. why?
Upvotes: 0
Views: 716
Reputation: 1171
Modify the values after ajax call returns success:
$('#btnAddNew').click(function(evt) {
$.ajax({
url: '@Url.Action("GetAllEmployee","Employee")',
method: 'GET',
dataType: 'json',
success: function(data) {
//edit form's ddl
$('#ddlEmployeeCategories').empty();
console.log(data);
$(data).each(function(index, item) {
//edit forms ddl
$('#ddlEmployeeCategories').append($('<option/>', {
text: item.Description,
value: item.ID
}));
});
$('#empID').val('');
$('#ddlEmployeeCategories').val('2');
$('#txtFirstName').val('');
$('#txtLastName').val('');
$('#txtDOB').val('');
$('#txtSalary').val('');
$('#cbIsMarried').prop('checked', false);
form.dialog('open');
resetValidations();
form.show();
},
error: function() {}
});
});
Upvotes: 1
Reputation: 4748
Change your success
to:
success: function (data) {
$('#ddlEmployeeCategories').empty();
$(data).each(function (index, item) {
$('#ddlEmployeeCategories').append($('<option/>', { text: item.Description, value: item.ID }));
});
$('#ddlEmployeeCategories').val('2');
... // your other code
}
You must set that item when you are certain that your ajax call has finished.
Upvotes: 1