Thanks for the additional details. Your code doesn’t work because it is wrapping the <div>
around the original <option>
element, not the element that the Select2 widget displays.
According to the Select2 documentation, you can use the following code to find the selected element:
$('#select').find(':selected');
But that element is in the original <select>
, not the Select2 widget. However, you can use that code to add a custom data-
attribute to the selected <option>
element when the “add” button is pressed; e.g., $('#select').find(':selected').attr('data-selected', 'true');
.
Then, you can create a custom templateResult callback for the Select2 widget that returns null
instead of the item’s text for any <option>
with that data-
attribute set. Returning null
from the templateResult callback hides the item when the Select2 widget is open.
Finally, you can remove the custom data-
attribute when the user removes the item from the container. How you would do that is up to you. If the <select>
is a single-select, then it’s easy (just find the selected element); but if it’s a multi-select, then you’ll have to figure out how to target the correct <option>
. That will depend on your data; for instance, whether each <option>
has a unique ID value, or some other way to uniquely identify it. As long as you store that unique identifier in the “container”, you should be able to use it to find the <option>
you need to unhide.
I hope this makes sense. Follow the links in my post for more details about each of those steps, and good luck!