I have a page with two drop downs (DropDownListFor) that are populated on load. One is a category and the other is the items that fit that category. There is a title (TextAreaFor) below that is updated to reflect the text in the second drop down.
<div class="form-group">
@Html.LabelFor(model => model.BLL_ID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-6">
@Html.DropDownListFor(model => model.BLL_ID, Model.BLL_Categories, new { @style = "max-width: 500px;" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BLL_2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-6">
@Html.DropDownListFor(model => model.BLL_2, SessionManager.CurrentBLL.OriginalBLL, new { @style = "max-width: 500px;" })
@Html.ValidationMessageFor(model => model.BLL_2, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Note, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-6">
@Html.TextAreaFor(model => model.Note, htmlAttributes: new { @class = "form-control", @rows = "3", @readonly = "true" })
</div>
</div>
The first drop down has a change event registered in JS that populates the second drop down. The second drop down has a change event that updates the title.
var categories = $("#BLL_ID");
var requests = $("#BLL_2");
$("#BLL_2").change(function () {
updateTitle();
});
categories.change(function () {
requests.find('option').remove();
$.getJSON('_Some_Page', { Category:
$("#BLL_ID>option:selected").val() }, function (data) {
$(data).each(function (index) {
$("<option value=" + this.Value + ">" + this.Text + "
</option>").appendTo(requests);
});
});
updateTitle();
});
function updateTitle() {
var title = $("#BLL_2>option:selected").text();
$("#Note").val(title);
}
The issue is regarding the title update during the first drop down change event. If I use the JS debugger, I notice that the second drop down is not populated yet when the updateTitle() function is called. Is there any way to wait until the drop down is populated to call the function?
I have found that by putting calls inside they will be fired sequentially. If they are outside then it will call the database and try to call the update before the database call has finished and will cause issues. Try changing your code like this