How to add icon to selected item in select2?

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?

+8
javascript jquery html css jquery-select2
source share
11 answers

Just replacing < with &lt; options and deleting format functions:

 <select id="sel" style="width: 100%"> <option value="1">Hello</option> <option value="2">Friends &lt;i class='fa fa-check'>&lt;/i></option> <option value="3">Stackoverflow</option> </select> 

You can test it here: http://jsbin.com/nasixuro/11/edit

+6
source share

I think there are two ways to achieve this:

  • The first solution is the best,

    you can make it work by simply defining the escapeMarkup function in select2 , and this function should return the same data as an input parameter without any changes.

    anything you need:

     $("#sel").select2({ escapeMarkup: function(m) { return m; } }); 

    here's a working example: http://jsbin.com/nasixuro/3/edit

  • second , make small changes to the select2.js file.

    after checking select2.js , I found a function that updates the text, and there was a small problem, select2.js . html to prevent js injection to make it work, as you expect to have html escaping and use the .html () function from jquery api to insert the html instead of the .append () function used in updateSelection select2. js .

    here is the function I'm talking about:

     // single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } }, 

    delete this:

     if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } 

    and change:

     if (formatted !== undefined) { container.append(formatted); } 

    in

     if (data !== undefined) { container.html(data.text); } 

    This is a dirty decision, in my opinion.

    For the Delete action, use this js code :

     $("#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; } }); 
+10
source share

Manbe, you can use the select2 parameter: formatResult or formatSelection, as shown below

 $(document).ready(function () { $("#sel").select2(); $("#addok").click(function() { $("#sel").select2({ //formatResult: format formatSelection: format //escapeMarkup: function(m) { return m; } }); }); }); function format(state) { if (!state.id) return state.text; return "<i class='fa fa-check'></i>" + state.text; } 

Jsbin

+3
source share

You do not need to manually manipulate the DOM

 var icon_checked = "<i class='fa fa-check'></i>"; function format(opt) { var selection = this.element.select2("val"); if (opt.id === selection) { return opt.text + icon_checked; } return opt.text; } $("#sel").select2({ formatResult: format }); 

Basically this.element returns an instance of the select element on which you can run .select2("val") to get the selected value.

Compare this to the object identifier, if true , then let the else HTML checkbox return plain text. I think this is what you tried to achieve.

Here is a working violin , I think this is what you tried to achieve

+3
source share

You cannot add tags inside an option. Try setting the font of the option as font-family: "myfontawesome", arial; and add a special character instead of replacing css.

+2
source share

I think your problem is that you cannot create style values ​​or add html to the elements in the drop-down list as you try ... it's plain text.

 newtext = actual_value + "wat"; 

See how your fiddle works when I remove html and just add plain text :

I also suggest looking here .

+1
source share

If you want the icon to display, you need to target the HTML element and insert HTML, not TEXT. more or less like this:

 $(document).ready(function () { $("#sel").select2(); $("#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>"; $("#s2id_sel").find('.select2-chosen').html(newtext); }); }); 

See http://jsfiddle.net/S9tE3/

BUT. The HTML element that you need to customize from what I see is $ (' s2id _ ' + [ current element identifier ]). s2, I think for SELECT2 and id_. So your choice is id = "sel", which means $('s2id_sel') . Also note that you need to find which one is selected. This is quite convenient, it has a .select2-selected class, which makes it easy to target.

This will not change the meaning, just LOOK , which I think you are definitely trying to do.

Hope that helps

+1
source share

Replace this code

  <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> 

and put this code

 <select id="sel" style="width: 100%"> <option value="1">Hello</option> <option value="2">Friends</option> <option value="3">Stackoverflow</option> </select> 
+1
source share

I changed a little code to check your data icon

  $("#addok").click(function() { actual_value = $("#sel").find(':selected').text(); if($("#sel").find(':selected').data('icon') == '1') { alert("asd"); return} 

Set data-icon = 0 to prevent it from creating an icon from format_select2_icon and remove the icon.

  if($("#sel").find(':selected').data('icon') == '1') { $("#sel").find(':selected').data('icon','0') ; $(".select2-chosen").text(actual_value).change(); } 

See: http://jsbin.com/nasixuro/18/edit

Hope this helps you.

+1
source share

With the fontawesome sign , you can use the following:

 .select2-results__option[aria-selected=true]::before { content: "\f0c9"; font: normal normal normal 14px/1 FontAwesome; color: rbg(255,0,0); } 

There is a text equivalent of each icon: http://fortawesome.imtqy.com/Font-Awesome/cheatsheet/

Or if you have a gif, for example, it works very well with your image as a CSS background as follows:

 .select2-results__option[aria-selected=true] { background: url('path/to/image.gif') no-repeat 10px 10px; } 

Here is the result:

drop-down list select with gif as icon

0
source share

With Bootstrap Glyphicons you can add the following to your CSS

 .select2-results__option[aria-selected=true]::after { font-family: "Glyphicons Halflings"; content: "\e013"; } 

and glyphicon-ok will be added to each selected item.

Check out the Bootstrap cheatsheet for icon codes.

0
source share

All Articles