Add image to programatically created Option?

I’m creating some Options, like this:

var newOption = new Option("whatever the value", "test", false, false);
('#mySelect2').append(newOption).trigger('change');

That creates this:

<select id="mySelect2" multiple="multiple">
	<option value="test">whatever the value</option>
</select>

But I’d like to have an image next to each item in the select. Any tips on creating options with images, programatically? I don’t see anyting about it in the manual.

Select2’s default output is just the text of the <option> elements in the HTML. However, you can create a custom render template that can output any HTML you want for each item in the Select2 dropdown.

Since you are populating your Select2 via <option> elements (generated dynamically, but still <option> elements), you must find a way to include whatever data you would need to display the images you want (e.g., the URL of each image) in the <option> elements. The “correct” way to do that is to set a property on the Option’s dataset property. For example, after creating your newOption object, but before appending it, you could do something like this:

var newOption = new Option("whatever the value", "test", false, false);
newOption.dataset.imgUrl = "http://your.site.com/your/image/path/image.png";
('#mySelect2').append(newOption).trigger('change');

That gets your image URL into the Option object (you may or may not see it in the HTML as the “data-img-url” attribute in your <option> element).

Next, your custom render template will get called for each item that is displayed in the Select2 dropdown. When it is called, Select2 will pass to your custom render template a single parameter. This parameter represents the internal data value that Select2 uses to represent your <option> elements (e.g., it’s id, text and disabled properties). Importantly, it also contains a property called element, which is a reference to the actual <option> element in the HTML. And from that element field you can reference its dataset.imgUrl value, and use that value as the src attribute for an <img> tag that you include in your custom render template’s output.

The custom render template example in the documentation link I provided above shows how to include an image in the items in the dropdown.