I want to add one icon to placeholder like this
$("#tag_list").select2({
allowClear: true,
placeholder: "<i class='icon-group'></i> inout your tags...",
tags: ['a', 'b', 'c'],
});
But it renders plain text in select2, so how to render html text for placeholder?
In select element we don’t have a placeholder attribute but we can add it by using <option> element with disabled, selected and hidden attribute. The disabled attribute makes the option unable to select.
For that purpose, many websites are replacing <select> elements with a custom-built solution powered by HTML and CSS. There does not exist a placeholder attribute for the <select> tag.
For multi-selects, you must not have an empty <option> element: Select2 uses the placeholder attribute on multiple select boxes, which requires IE 10+. You can support it in older versions with the Placeholders.js polyfill. Alternatively, the value of the placeholder option can be a data object representing a default selection ( <option> ).
For single selects only, in order for the placeholder value to appear, you must have a blank <option> as the first option in your <select> control. This is because the browser tries to select the first option by default. If your first option were non-empty, the browser would display this instead of the placeholder.
Select2 automatically escapes HTML markup.
$("#tag_list").select2({
allowClear: true,
placeholder: "<i class='icon-group'></i> inout your tags...",
tags: ['a', 'b', 'c'],
escapeMarkup : function(markup) { return markup; } // let our custom formatter work
});
By overriding the 'escapeMarkup' parameter you can force it to render plain HTML instead (by returning the unescaped HTML as is). This will affect both the placeholder AND the select data (select2 handles the placeholder as any data, thus escaping it).
For more information, check the AJAX data example: Examples - Select2 | LoadingRemoteData
You can specify a placeholder object, rather than only the text. This will render the HTML.
So in your case, the placeholder might look something like this.
$("#tag_list").select2({
placeholder: {
id: "-1",
text: '<i class="icon-group"></i> input your tags...'
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With