Home > Software design >  Changing the color of a dropdown in JavaScript
Changing the color of a dropdown in JavaScript

Time:05-20

Unfortunately, I could not find any given solution to solve my problem.

I need to change a specific option's color in a given dropdown .

EDIT: This is the HTML:

<label> Select Lec:</label>
   <select id="lect">
      <option value="0"> Select</option>
   </select>

This is where I call the function changeColor:

$("#algorithmResult").append("<p class='added_value'>Recommended: "   algorithm_result[course].Lec_name   "</p>");
changeColor(algorithm_result[course].Lec_name);

This is the following code:

$("#lect").append("<option id='"   res[i].Lec_name "'  >"   res[i].Lec_name   "</option>");

Now I have the following function triggered:

function changeColor(value) {                   
            document.getElementById(value).style.color = "green";

        }

Now, I have debbuged and res[i].Lec_name and value are the same string. For some reason it doesn't work, can someone help ?

CodePudding user response:

You can always use Inspect Element in your browser, find the dropdown with the initial color (you should see, background: #fff or background: white, for example. Then look at the css selector above and change the background color directly from the css file (or html style) of your code.

.selectize-dropdown {
  background: "green";
 }

CodePudding user response:

if i understand it right you are trying to highlight options so i have created a simple function for it where you have to give select element in first param then array of indexes to assign selected class on it then put style to that class in css

function changeColor(select,indexes){
    Array.from(select.children).forEach((each,i)=>{
        if(indexes.indexOf(i) === -1){
            each.classList.remove("selected")
        }
        else {each.classList.add("selected")}
    })
}


//example use
const select = document.querySelector("select")
changeColor(select,[0,3,5,8]) // [main select element , indexes to highlight]
.selected {
  background:blue;
  color:white;
}
<select name="" id="">
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
    <option value="select1">select1</option>
</select>

  • Related