Select2 Font Awesome Icon on Placeholder

让人想犯罪 __ 提交于 2020-05-10 15:39:04

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/35405269/select2-font-awesome-icon-on-placeholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!