select2: Select2 v4 marking an option as selected does not refresh, instead duplicates element
I’m trying to mark an option as selected through another field value but the select2 control does not show the selection, instead duplicates the element with a disabled selected option (to the left). The parent select is updated from another field in an iframe. The option update works without select2 enabled. I use the following code for the same.
$('.searchrow').click(function (e) {
var srchdata = $(this).data('search').split("|");
var target = ".srchtarget-" + $(this).data('target');
var targetoption = target + " option[value='" + srchdata[0] + "']";
var parentctrl = window.parent.document;
$(targetoption,parentctrl).attr("selected","selected");
$(target,parentctrl).select2();
});
This outputs the following:

Note that the option is also selected correctly in the select2 control.
Using $(target,parentctrl).val(srchdata[0]).select2(); gives similar results too.
I tried to destroy the select2 before update, but that gives an error that ‘destroy’ option is applied in an element that is not using select2.
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 20 (6 by maintainers)
I have a similar problem.
I have a select2 field with ajax query, and a pre-selected option. The ajax query is displayed correctly but when I select an entry, it appends the entry to the list of options and do not update the “selected” property, keeping it on the previous (and original) option.
@Alexweissman: No. I no longer have this issue. I had solved this long ago and have given the solution in the comment above @dehy.
@Others: If the option is preselected while loading the page, you’ll have to deselect it with
$(elem).attr()while you receive the Ajax response. This is because the selected attribute is part of the page html and not js dom. If the option is being selected in the dom (by the user after loading the page), you can manipulate it with.prop(). Please see my solution for an example.Two things
changeevent after you change the value of an input on a page, it’s what JS controls use to determine if there was a change. Browsers trigger it natively, you can trigger it in JS with$('select').trigger('change').selectedproperty of the<option>instead of the attribute. This is what Select2 uses, and it’s part of the native DOM specification forHTMLOptionElement. The main difference here is calling.prop('selected', true)instead ofattr('selected', 'selected').If your issue isn’t fixed after making these changes, can you wrap this up into a small test case (hosted on jsbin or jsfiddle) where we can reproduce the issue?