Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 Font Awesome Icon on Placeholder

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.

like image 800
cocksparrer Avatar asked Feb 15 '16 09:02

cocksparrer


1 Answers

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>
like image 150
Alessio Cantarella Avatar answered Oct 12 '22 16:10

Alessio Cantarella