I have the code below where I am creating dynamic Select Elements. The control is displayed on the browser with no issues. However, the option I select is not the one selected on the screen. The screen always shows the last item.
What is odd is if I View Source, the “select” property is on the option I selected. However, the last option is being shown.
I tried using .attr("selected", value === selectOption.SelectedValue)) and that does not even add the “selected” property on the option element.
The only thing that seems to work is selecting the value after the Select Element has been appended to my div tag (commonSubjectivesWindow). But that seems hacky to me.
Been Googling this problem for hours. Any suggestions would be helpful.
function createSelectElement(commonSubjective, selectOption) {
var name = "select" + commonSubjective.Id;
var selectElement = $("<select>").attr("name", name);
//Tried, does not work
//$.each(selectOption.Options, function (key, value) {
// selectElement.append($("<option>").val(value).text(value).prop("selected", value === selectOption.SelectedValue));
//});
$.each(selectOption.Options, function (key, value) {
selectElement.append($("<option>").val(value).text(value).attr("selected", value === selectOption.SelectedValue));
});
return selectElement;
}
function formatCommonSubjectiveText(commonSubjective) {
if (commonSubjective.SelectOptions.length > 0) {
var i = 0;
$.each(commonSubjective.SelectOptions, function() {
var selectElement = createSelectElement(commonSubjective, this);
var placeHolder = "{" + i + "}";
commonSubjective.Text = commonSubjective.Text.replace(placeHolder, selectElement.prop("outerHTML"));
i++;
});
}
return commonSubjective.Text;
}
function loadCommonSubjectives() {
var commonSubjectivesJson = JSON.parse($("#commonSubjectivesHidden").val());
$.each(commonSubjectivesJson, function () {
$("#commonSubjectivesWindow").append($("<span>").append(formatCommonSubjectiveText(this)).prepend(
$("<input>").attr("name", "CommonSubjectivities").attr("type", "checkbox").val(this.Id).prop("checked", this.IsSelected)
).after("</br></br>"));
});
}