How to select ListBox items after appending through JQuery?

Viewed 24

I have got a ListBox in my view to which I am appending items using JQuery. I am able to append the items successfully but I cannot figure out how to select the required items which were appended.

My ListBox:

@Html.ListBoxFor(model => model.InternalEmailFileUploadIds, new MultiSelectList(new[] { "" }, Model.InternalEmailFileUploadIds), new { @class = "form-control select2-multiselect-checkbox", @placeholder = "File Upload Controls", multiple = "multiple", id = "internalEmailFileUpload" })

Jquery to append items:

$.each(response, function (i, item) {$('#internalEmailFileUpload').append('<option value="' + item.Id + '">' + item.Label + '</option>');})

The InternalFileUploadIds variable in the model is populated but that doesn't seem to help.

My view consists of multiple tabs and I am not appending the items on page load. I am appending the items when the correct tab is clicked.

1 Answers

Turned out to be quite a simple answer in the end.

Needed a selected in the required options that were added.

$('#internalEmailFileUpload').append('<option value="' + item.Id + '" selected>' + item.Label + '</option>');

Related