Select2 Font Awesome Icon on Placeholder
Asked Answered
S

1

6

How to add FontAwesome before the placeholder text on Select2.

This is my Select2 option code:

var placeholder = "<i class='fa fa-search'></i>  " + "Select a places";
$(".select2").select2({
    placeholder: placeholder,
    width: null
});

This is my HTML code:

<select class="form-control select2">
    <option></option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>

Thank you.

Singlehanded answered 15/2, 2016 at 9:10 Comment(10)
what do you mean with 'before' ?Quadrisect
Select box has not placeholder property.. so please use first option to placeholder.Objectivism
I'm sorry, I mean the icon is on the left of the placeholder text.Singlehanded
@javedrathod, thank you for the comment, but select2 has it.Singlehanded
i think you want search icon before select 2 right?Objectivism
#19350791 this might be helpful. :)Acumen
@javedrathod, yes. but I hope it can be editable so I can change it with different icon someday.Singlehanded
<i class='fa fa-search'></i> <select><option>test</option></select> just like thisObjectivism
@AjayMakwana, thank you I've been there. unfortunately, like javedrathod said, select box has not placeholder property. that page you refer are for input box.Singlehanded
@Singlehanded take a look at my answer.Disorganize
D
10

Declare the escapeMarkup function between Select2 options, then use "search" icon code (you can find it in the Font-Awesome Cheatsheet page) for the placeholder:

$(function() {
  var placeholder = "&#xf002 Select a place";
  $(".select2").select2({
    placeholder: placeholder,
    width: null,
    escapeMarkup: function(m) { 
       return m; 
    }
  });
});
.select2 {
  font-family: 'FontAwesome'
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>

<select class="form-control select2">
  <option></option>
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>
Disorganize answered 15/2, 2016 at 9:44 Comment(5)
Worked successfully. Thank you!Singlehanded
@MarcosDiPaolo that was the case of his question 😉Disorganize
hi @AlessioCantarella, yes. Do you have a way of using a non escaped placeholder in a mmultiple select?Unchaste
@MarcosDiPaolo create a new question on StackOverflowDisorganize
@AlessioCantarella sorry you're right. Here's my question: #60141938Unchaste

© 2022 - 2024 — McMap. All rights reserved.