如何在select2中添加html占位符?

时间:2013-07-27 08:57:09

标签: placeholder jquery-select2

我想在此占位符中添加一个图标

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

});

但它在select2中呈现纯文本,那么如何为占位符呈现html文本?

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

我猜你正在尝试使用font-awesome。 他们在这里有一张带有unicodes的备忘单:http://fortawesome.github.io/Font-Awesome/cheatsheet/ 这可以放在html中的占位符:

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

请记住在输入元素上添加:

font-family: 'FontAwesome'

所有浏览器都不支持此功能,因此您可能希望使用:before元素执行回退操作。

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

最后的后备是实际使用这样的图像:

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

如果您想要删除焦点上的图标,请添加:

input:focus {
 background-position: -20px center;
 text-indent: 0;
 width: 50%;
}

答案 2 :(得分:0)

您可以指定一个占位符对象,而不仅仅是文本。这将呈现HTML。

因此,在您的情况下,占位符可能看起来像这样。

$("#tag_list").select2({
    placeholder: {
        id: "-1",
        text: '<i class="icon-group"></i>  input your tags...'
    }
});

答案 3 :(得分:-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/