0
votes

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>"));
    });

}
2
can you link a fiddle for it?Pardeep Dhingra

2 Answers

0
votes

Strange, just made a fiddle ... added a selectbox dynamically (just one) and selected an item ... even if appended after setting the value.

Fiddle here

Just set the value with:

selectElement.val('val2');

From jquery docs

val() allows you to pass an array of element values. This is useful when working on a jQuery object containing elements like , , and s inside of a .

0
votes

I'm not 100% sure what you want, so I'll simplify the answer, then you let me know if it is or isn't what you meant.

What I understand:

  • Creating a <select> dynamically
  • Having trouble adding the selected attribute to an <option>

Ok, for this example, I'm using plain JS, it can be easily adapted into jQuery. The biggest challenge there is to remember which objects are normal ones and which are jQuery objects.

function makeSelect(ele, len, att) {
  var sel = document.createElement("select");
  var tgt = document.querySelector(ele);
  sel.id = "selectList";
  tgt.appendChild(sel);

  for (var i = 1; i < len + 1; i++) {
    var opt = document.createElement("option");
    opt.text = i;
    opt.value = i;
    sel.appendChild(opt);
  }
  sel.selectedIndex = att - 1;
}

makeSelect('#set', 10, 5);
body {
  background: #111;
}
#set {
  border-radius: 8px;
  width: 5em;
  background: #222;
  border: 2px inset #FC3;
}
legend {
  font: small-caps 400 21px/1.5 "Palatino Linotype";
  color: #FC3
}
<fieldset id="set">
  <legend>DynSelect</legend>
</fieldset>

Usage makeSelect(ele, len, att)

  • ele: The selector of the element that the <select> will append to. (i.e. selectors - #id, .class, tag).
  • len: The number of options.
  • att: The index of the selected option.

The heart of this post concerning your question can be summarized with this:

Use .selectedIndex

Forgive me for using a W3School reference, MDN doesn't have it listed. If anyone has found a better reference please notify me in comments.