I have a select dropdown in my webpage created dynamically as
<select id="mainDropDown" class="Field">
<option data-id="-1">Select your option</option>
</select>
I have it dynamically populated, when another event (button click) occurs
$('body').on("click", "#addOption", function () {
createOption();
$('#mainDropDown').val($("#newOption").val()).trigger('change');
$("#newOption").val("")
});
function createOption()
{
for (var k in OptionList) { // OptionList has the list of options already added to the dropdown
tempSelectedState = "";
if ($("#newOption").val() == OptionList[k].name) {
tempSelectedState = "selected";
}
$("#mainDropDown").append("<option data-id='" + OptionList[k].ID + "' " + tempSelectedState + ">" + OptionList[k].name + "</option>");
//$('body #mainDropDown').val().trigger('change');
}
}
Here the problem, is the select change event is not getting called.
$('#mainDropDown').change(function () {
//.................
}
I am trying to call it explicitly at
$('#mainDropDown').val($("#newOption").val()).trigger('change');
But when this is called, The dynamically added option to the mainDropDown is not populated yet, and hence not accessible.
The actual functionality needed is when a new option is added, it must be selected by default, also the value change event must be triggered successfully.
