Dynamic select lists
Dynamic select lists
I'm encountering a snag when attempting to dynamically populate multiple dynamic select elements. I have the following object hierarchy Field --> Category --> Expertise which are displayed within a form as select elements, e.g., when 'Field' is changed then the 'Category' is repopulated based on the root index value of 'Field' and then 'Expertise' is repopulated based on the root index value of 'Category'. Below is the code I'm using:
- <div class="formRow">
<label class="desc" for="Job_Field">
Field:</label>
<div class="col">
<%= this.Select("Job.Field")
.Options(ViewData.Model.Fields, u => u.Id, u => u.Name)
.Selected((ViewData.Model.Job.Field != null) ? ViewData.Model.Job.Field.Id : 0)
.Class("select") %>
</div>
</div>
<script type="text/javascript">
// Populate category by field
$(document).ready(function () {
$.post('/Admin/Job/GetCategoryByField', { id: $('#Job_Field').val() }, function (data) {
populateDropdown($('#Job_Category'), data);
});
});
</script>
<div class="formRow">
<label class="desc" for="Job_Category">
Category</label>
<div class="col">
<%= this.Select("Job.Category")
.Selected((ViewData.Model.Job.Category != null) ? ViewData.Model.Job.Category.Id : 0)
.Class("select") %>
</div>
</div>
<script type="text/javascript">
// Populate expertise by category
$(document).ready(function () {
$.post('/Admin/Job/GetExpertiseByCategory', { id: $('#Job_Category').val() }, function (data) {
populateDropdown($('#Job_Expertise'), data);
});
});
</script>
<div class="formRow">
<label class="desc" for="Job_Expertise">
Expertise</label>
<div class="col">
<%= this.Select("Job.Expertise")
.Selected((ViewData.Model.Job.Expertise != null) ? ViewData.Model.Job.Expertise.Id : 0)
.Class("select") %>
</div>
</div>
And the 'populateDropdown' function:
- <script type="text/javascript">
// Populate dropdown
function populateDropdown(select, data) {
select.html('');
$.each(data, function (id, option) {
select.append($('<option></option>').val(option.Value).html(option.Text));
});
}
</script>
Currently on page load 'Category' is repopulated but 'Expertise' is not. A null is being returned as the value of 'Category' element. I've attempted to set the selected index of 'Category' prior to repopulating 'Expertise' but it does not help:
- $('#Job_Category').attr('selectedIndex', 0);
I believe it may be a synchronous issue with the post method because 'Expertise' will repopulate if I add an alert before the call to repopulate. The short delay caused by the alert seems to provide significant amount of time for 'Expertise' to be repopulated. Does anyone have any suggestions as how to resolve this item?
Thanks!