问题
I using select2 version 4
I try like this :
$("select02").select2({
placeholder: "<i class='fa fa-sitemap'></i>Branch name",
});
But, it's not working
Demo is like this : http://jsfiddle.net/fc1qevem/8/
Any solution to solve my problem?
回答1:
Always read the reference/manual first!
From the official select2 examples on their web site;
function formatState (state) {
if (!state.id) { return state.text; }
var $state = $(
'<span><img src="vendor/images/flags/' + state.element.value.toLowerCase() +
'.png" class="img-flag" /> ' +
state.text + '</span>'
);
return $state;
};
$(".js-example-templating").select2({
templateResult: formatState
});
Gives you the result:
回答2:
Found this How to add html placeholder to select2?
So what you need is:
$("select02").select2({
placeholder: '<i class="fa fa-sitemap"></i>Branch name',
escapeMarkup : function(markup) {
return markup;
}
});
回答3:
For Icons instead of img use:
function format (state) {
if (!state.id) { return state.text; }
return '<i class="fa fa-lg '+state.id.toLowerCase()+'"></i> '+state.text;
}
$("#select2icon").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
回答4:
Here is working example:
function format(state) {
if (!state.id)
return state.text; // optgroup
return "<img class='flag' src='images/flags/" + state.id.toLowerCase() + ".png'/>" + state.text;
}
$("#select2").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
user above js.
回答5:
You almost had it. You just need to add 'escapeMarkup'. See the code below.
var select02 = $('#select02');
$(select02).select2({
data: [{
id: 0,
text: "test01"
}, {
id: 1,
text: "test02"
}, {
id: 2,
text: "test03"
}, {
id: 3,
text: "test04"
}, {
id: 4,
text: "test05"
}],
placeholder: "<i class='fa fa-sitemap'></i>Branch name",
escapeMarkup: function (markup) { return markup; }
});
回答6:
Per the migration guide, versions after 3.5.x no longer use formatResult
or formatSelection
. These have been replaced with templateResult
and templateSelection
.
function iconFromValue(val){
if(val.element){
val = `<span class="select2-option-img"><img src="${val.element.value}"><span> ${val.text}`;
}
return val;
}
$(document).ready(function() {
$('.select2').select2({
templateResult: iconFromValue,
templateSelection: iconFromValue,
escapeMarkup: function(m) { return m; }
});
}
来源:https://stackoverflow.com/questions/37386293/how-to-add-icon-in-select2