How to add html placeholder to select2?
Asked Answered
O

4

6

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?

Ontology answered 27/7, 2013 at 8:57 Comment(1)
Does it work if you remove the quotes? Also, post your code in a fiddle, if possible.Archaeology
P
6

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

Pegram answered 11/7, 2016 at 19:2 Comment(0)
P
1

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...'
    }
});
Petrick answered 3/7, 2018 at 5:54 Comment(0)
L
0

Im guessing your are trying to use font-awesome. They have a cheatsheet with unicodes here: http://fortawesome.github.io/Font-Awesome/cheatsheet/ This can be placed in the placeholder in html:

<input name="username" placeholder="&#xf042;">

Remember to add the on the input element:

font-family: 'FontAwesome'

This is not supported by all browsers so you might want to do a fallbackhack with the :before element.

.wrapper:before {
  font-family: 'FontAwesome';
  color:red;
  position:relative;
  content: "\f042";
}

Last fallback is to actually use an image like this:

background-image: url(http://www.levenmetwater.nl/static/global/images/icon-search.png);
background-position: 10px center;
background-repeat: no-repeat;

If you want it to remove the icon on focus, add this:

input:focus {
 background-position: -20px center;
 text-indent: 0;
 width: 50%;
}
Lieberman answered 2/10, 2014 at 7:32 Comment(0)
S
-1
function format(state){

if (!state.id) {

return state.text; // optgroup

} else {

return "<img class='flag' src='images/flags/" + state.id.toLowerCase() + ".png'/>" + state.text;

}

}

$("#tag_list").select2({

    formatResult: format,

    formatSelection: format,

    escapeMarkup: function(m) { return m; }


});

http://ivaynberg.github.io/select2/

Salot answered 27/7, 2013 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.