I'm using fontawesome, and I want to add or remove an icon to the selected item. So I did this: http://jsbin.com/nasixuro/7/edit (Thanks to @Fares M.)
JS
$(document).ready(function () {
function format_select2_icon(opti) {
if (!opti.id) return opti.text; // optgroup
if ($(opti.element).data('icon') == "1") {
return opti.text + " <i class='fa fa-check'></i>";
} else {
return opti.text;
}
}
$("#sel").select2({
escapeMarkup: function(m) { return m; },
formatResult: format_select2_icon,
formatSelection: format_select2_icon
});
$("#addok").click(function() {
actual_value = $("#sel").find(':selected').text();
if (actual_value.indexOf(" <i class='fa fa-check'></i>") > -1){
alert("asd");
return;
}
newtext = actual_value + " <i class='fa fa-check'></i>";
$("#sel").find(':selected').text(newtext).change();
});
$("#removeok").click(function() {
actual_value= $("#sel").find(':selected').text();
indexOk=actual_value.indexOf(" <i class='fa fa-check'></i>");
if (indexOk > -1){
newtext =actual_value.substring(0, indexOk);
$("#sel").find(':selected').text(newtext).change();
return;
}
});
});
HTML
<select id="sel" style="width: 100%">
<option value="1">Hello</option>
<option value="2" data-icon="1">Friends</option>
<option value="3">Stackoverflow</option>
</select>
<br><br>
<button id="addok">Add <i class='fa fa-check'></i></button>
<button id="removeok">Remove <i class='fa fa-check'></i></button>
As you see, you can add or remove the icon in Hello
and Stackoverflow
items, but in Friends
(that is the option formated with formatSelection
and formatResult
), does not remove the icon, and if you try to add the icon, the appends another one to the existing.
Do you have any idea to solve this?