How to add html placeholder to select2?

泪湿孤枕 提交于 2019-12-10 21:37:50

问题


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?


回答1:


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




回答2:


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%;
}



回答3:


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...'
    }
});



回答4:


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/



来源:https://stackoverflow.com/questions/17896075/how-to-add-html-placeholder-to-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!