简体   繁体   中英

set option style on load for select element

I have the following on load of my web page:

<script>     
function updateStateSelectColor(){
  var elm = document.getElementById("state");
  elm.style.color="black";
}
</script>

<select id="state" onchange="updateStateSelectColor()">
  <option value="AL">Alabama</option>
  <option value="FL" selected>Florida</option>
</select>

What I want is when the page loads for the selected text inside the state select box to be bolded black just like my onchange function that blackens the text. The problem is my JavaScript is only for onchange not onload .

There are multiple ways to achieve this.

  1. Use document.addEventListener() to add a callback for the DOMContentLoaded event:

 document.addEventListener("DOMContentLoaded", function(event) { updateStateSelectColor(); }); function updateStateSelectColor(){ var elm = document.getElementById("state"); elm.style.color="green"; } 
 <select id="state" onchange="updateStateSelectColor()" style="color: red"> <option value="AL">Alabama</option> <option value="FL" selected>Florida</option> </select> 

And one could even bind the function directly to the event listener, but bear in mind that the function would receive a reference to the event as the first argument.

      document.addEventListener("DOMContentLoaded", updateStateSelectColor);
  1. Assign the function to the window.onload property

 window.onload = function(event) { updateStateSelectColor(); }; function updateStateSelectColor(){ var elm = document.getElementById("state"); elm.style.color="green"; } 
 <select id="state" onchange="updateStateSelectColor()" style="color: red"> <option value="AL">Alabama</option> <option value="FL" selected>Florida</option> </select> 

  1. use the onload attribute of the <body> tag

  2. Invoke the function immediately after it is defined (as was described in bassxzero's comment ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM