'individual background colour of options in <select> based on map
I would like to set an individual background colour of each option of a <select> with Javascript. The option text and colour (hex) are stored in a Map:
const map = new Map();
map.set("005", "#886da8");
map.set("0075", "#ffc3cf");
for (const [key, value] of map.entries()) {
console.log(key, value);
$('#cmbExample').append($('<option>', {
value: key,
text : key
}));
}
Finally it should look like this:
Solution 1:[1]
You just have to set the style attribute with a background property using the value.
Templating literals is helpful here.
const map = new Map();
map.set("005", "#886da8");
map.set("0075", "#ffc3cf");
map.set("01", "#ef9b00");
map.set("015", "#2bb430");
map.set("02", "#f7dc01");
map.set("025", "#bc65a2");
map.set("03", "#487ebf");
map.set("04", "#e00124");
map.set("05", "#b36634");
map.set("06", "#949494");
map.set("08", "#ffffff");
map.set("10", "#000000");
map.set("12", "#4bbbd0");
map.set("16", "#8b6d9f");
map.set("20", "#8ccff4");
for (const [key, value] of map.entries()) {
// console.log(key, value);
$('#cmbExample').append($('<option>', {
value: key,
text: key,
style: `background: ${value}` // Set the style like this
}));
}
// Select element
let coulouredSelect = document.querySelector("#cmbExample")
// change event callback
setSelectColor = function(){
let value = coulouredSelect.value
coulouredSelect.style.backgroundColor = coulouredSelect.querySelector(`option[value='${value}']`).style.background
}
// change event listener
coulouredSelect.addEventListener("change", setSelectColor)
// on page load
setSelectColor()
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container">
<form>
<select id="cmbExample" class="form-select mt-3">
</select>
</form>
</div>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

