最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Font awesome in select menu - Stack Overflow

programmeradmin0浏览0评论

I want to add icons in my select menu. In one of Stack Overflow pages I have found that I can use Font Awesome and insert icon as a text. I included script in head part. When I tried to use icon in a select menu, it was not working. But it works outside select menu perfectly. Is it possible to insert icon in a select menu option or it is simply impossible to do? How can I do it?

There is a link to font awesome page:

There is a snippet of what I tried

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src=".js"></script>
  
</head>
<body>
	<i class="fas fa-truck">Truck</i>
	<br><br><br>
	<select>
		<option><i class="fas fa-truck">Truck</i></option>
	</select>
 
</body>
</html>

I want to add icons in my select menu. In one of Stack Overflow pages I have found that I can use Font Awesome and insert icon as a text. I included script in head part. When I tried to use icon in a select menu, it was not working. But it works outside select menu perfectly. Is it possible to insert icon in a select menu option or it is simply impossible to do? How can I do it?

There is a link to font awesome page: https://fontawesome./cheatsheet/free/solid

There is a snippet of what I tried

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://kit.fontawesome./9593bd7a92.js"></script>
  
</head>
<body>
	<i class="fas fa-truck">Truck</i>
	<br><br><br>
	<select>
		<option><i class="fas fa-truck">Truck</i></option>
	</select>
 
</body>
</html>

Share Improve this question asked Aug 30, 2019 at 16:58 vytautevytaute 1,5304 gold badges23 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

This is a limitation of HTML. select and option elements are native to HTML and do not have the ability to display HTML within them.

You'll need to mimic a select element with HTML, CSS + JavaScript and then map the value to a hidden input element (if you're using it as part of a form).

<ul class="select">
    <li class="option"><i class="fas fa-truck">Truck</i></li>
    <li class="option"><i class="fas fa-star">Star</i></li>
    <li class="option"><i class="fas fa-user">User</i></li>
</ul>

This can help for providing insight on the interactive aspect of your dropdown (so it does more than just display as a list): https://www.w3schools./howto/howto_js_dropdown.asp

Here is my solution

By default i tags are stripped from options in HTML

Add icons in the following method

 <option>&#xf0d1; Truck</option>

Also add following CSS

select,option {
    font-family: 'Arial', 'Font Awesome 5 Pro';
    font-weight: 900;
}

Replace the "Arial" font with your website font name.

Replace the middle code with the icon code of your choice

'&#x' + 'f0d1'(fontawsome truck icon code) + ;

The icon code can be found by right clicking on icon and checking the before pseudo element of the i tag of an icon.

select,option {
    font-family: 'Arial', 'Font Awesome 5 Pro';
    font-weight: 900;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <script src="https://kit.fontawesome./9593bd7a92.js"></script>

</head>

<body>
  <i class="fas fa-truck">Truck</i>
  <br><br><br>
  <select>
    <option>&#xf0d1; Truck</option>
    <option>&#xf0d1; Truck</option>
    <option>&#xf0d1; Truck</option>
    <option>&#xf0d1; Truck</option>
  </select>

</body>

</html>

Updated Answer

Since the above answer doesn't work on phones, you will have to implement custom select

Following is the code from w3schools how to create custom select

I modified the code to add support for icons.

var x, i, j, selElmnt, a, b, c;


function generateInnerDiv(index) {
  nametag = document.createElement("span");
  nametag.textContent = selElmnt.options[index].textContent;
  icon = document.createElement("i");
  icon.setAttribute("class", selElmnt.options[index].getAttribute('data-icon'));
  return [icon, nametag]
}


/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  /*for each element, create a new DIV that will act as the selected item:*/
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");


  innerDiv = generateInnerDiv(selElmnt.selectedIndex)
  a.appendChild(innerDiv[0]);
  a.appendChild(innerDiv[1]);


  //a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /*for each element, create a new DIV that will contain the option list:*/
  b = document.createElement("DIV"); //items holder
  b.setAttribute("class", "select-items select-hide");


  for (j = 1; j < selElmnt.length; j++) {
    /*for each option in the original select element,
    create a new DIV that will act as an option item:*/
    c = document.createElement("DIV");

    innerDiv = generateInnerDiv(j);
    c.appendChild(innerDiv[0]);
    c.appendChild(innerDiv[1]);

    //c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {

      /*when an item is clicked, update the original select box,
      and the selected item:*/
      var y, i, k, s, h, l, m;
      s = this.parentNode.parentNode.getElementsByTagName("select")[0];
      h = this.parentNode.previousSibling;
      l = this.getElementsByTagName("span")[0];
      m = this.getElementsByTagName("i")[0];


      for (i = 0; i < s.length; i++) {
        if (s.options[i].innerHTML == l.innerHTML) {

          s.selectedIndex = i;
          h.getElementsByTagName("span")[0].innerHTML = l.innerHTML;
          h.getElementsByTagName("i")[0].setAttribute("class", s.options[i].getAttribute('data-icon'));
          y = this.parentNode.getElementsByClassName("same-as-selected");
          for (k = 0; k < y.length; k++) {
            y[k].removeAttribute("class");
          }
          this.setAttribute("class", "same-as-selected");
          break;
        }
      }
      h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /*when the select box is clicked, close any other select boxes,
    and open/close the current select box:*/
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /*a function that will close all select boxes in the document,
  except the current select box:*/
  var x, y, i, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  for (i = 0; i < y.length; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < x.length; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}
/*if the user clicks anywhere outside the select box,
then close all select boxes:*/
document.addEventListener("click", closeAllSelect);


//////////////////
//How to get values from custom select
//////////////////
document.getElementById("btn1").addEventListener("click", () => {
  console.log(document.getElementById("myselect1").value)
});

document.getElementById("btn2").addEventListener("click", () => {
  console.log(document.getElementById("myselect2").value)
});
.custom-select {
  position: relative;
  font-family: Arial;
}

.custom-select select {
  display: none;
  /*hide original SELECT element:*/
}

.custom-select i {
  margin-right: 10px;
}

.select-selected {
  background-color: DodgerBlue;
}


/*style the arrow inside the select element:*/

.select-selected:after {
  position: absolute;
  content: "";
  top: 14px;
  right: 10px;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-color: #fff transparent transparent transparent;
}


/*point the arrow upwards when the select box is open (active):*/

.select-selected.select-arrow-active:after {
  border-color: transparent transparent #fff transparent;
  top: 7px;
}


/*style the items (options), including the selected item:*/

.select-items div,
.select-selected {
  color: #ffffff;
  padding: 8px 16px;
  border: 1px solid transparent;
  border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
  cursor: pointer;
  user-select: none;
}


/*style items (options):*/

.select-items {
  position: absolute;
  background-color: DodgerBlue;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 99;
}


/*hide the items when the select box is closed:*/

.select-hide {
  display: none;
}

.select-items div:hover,
.same-as-selected {
  background-color: rgba(0, 0, 0, 0.1);
}
<script src="https://kit.fontawesome./9593bd7a92.js"></script>

<h2>Custom Select</h2>

<!--surround the select box with a "custom-select" DIV element. Remember to set the width:-->
<div class="custom-select" style="width:200px;">
  <select id="myselect1">
    <option data-icon="fas fa-truck" value="0">Select car:</option>
    <option data-icon="fas fa-adjust" value="Audi">Audi</option>
    <option data-icon="fas fa-truck" value="BMW">BMW</option>
    <option data-icon="fas fa-arrow-up" value="Citroen">Citroen</option>
    <option data-icon="fas fa-asterisk" value="Ford">Ford</option>
    <option data-icon="fas fa-arrow-left" value="Honda">Honda</option>
    <option data-icon="fas fa-arrow-down" value="Jaguar">Jaguar</option>

  </select>
</div>

<br />
<div class="custom-select" style="width:200px;">
  <select id="myselect2">
    <option data-icon="fas fa-truck" value="0">Select car:</option>
    <option data-icon="fas fa-adjust" value="Audi">Audi</option>
    <option data-icon="fas fa-truck" value="BMW">BMW</option>
    <option data-icon="fas fa-arrow-up" value="Citroen">Citroen</option>
    <option data-icon="fas fa-asterisk" value="Ford">Ford</option>
    <option data-icon="fas fa-arrow-left" value="Honda">Honda</option>
    <option data-icon="fas fa-arrow-down" value="Jaguar">Jaguar</option>

  </select>
</div>

<br />
<h3>For testing Purpose<h3>

<button id="btn1">
   Console log Select 1 value
 </button>


<button id="btn2">
   Console log Select 2 value
 </button>

发布评论

评论列表(0)

  1. 暂无评论