Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add html placeholder to select2?

I want to add one icon to placeholder like this

$("#tag_list").select2({
    allowClear: true,
    placeholder: "<i class='icon-group'></i> &nbsp;&nbsp; inout your tags...",
    tags: ['a', 'b', 'c'],

});

But it renders plain text in select2, so how to render html text for placeholder?

like image 638
why Avatar asked Jul 27 '13 08:07

why


People also ask

How to add placeholder in select element in HTML5?

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.

Is there a placeholder attribute for the <select> Tag?

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.

How to support multi-selects with placeholders in Select2?

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> ).

Why can't I see a placeholder value in my select options?

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.


2 Answers

Select2 automatically escapes HTML markup.

$("#tag_list").select2({
    allowClear: true,
    placeholder: "<i class='icon-group'></i> &nbsp;&nbsp; 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

like image 65
Daniel Avatar answered Sep 21 '22 07:09

Daniel


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...'
    }
});
like image 45
Dan Avatar answered Sep 20 '22 07:09

Dan