I am using fontawesome and I want to add or remove an icon for the selected item. So I did this: http://jsbin.com/nasixuro/7/edit (Thanks @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 can see, you can add or remove an icon in the Hello and Stackoverflow , but in Friends (this is an option created using formatSelection and formatResult ) it does not delete the icon, and if you try to add the icon, add another one to the existing one.
Do you have an idea to solve this problem?
javascript jquery html css jquery-select2
harrison4
source share