0

I am dabbiling with NodeJS Express. On a page that is routed to from a home page I have a drop down box as seen here

The onchange event works great and was a solution I found from here

My goal is to have the background color from the CSS set on page load, either through an onload event or with javascript/jQuery.

I tried substituting onload in place of onclick

onload="this.className=this.options[this.selectedIndex].className">

which didn't work.

The option value to use when the page loads is selected from a database so it could be different every time this page is called. This doesn't need to be browser specific as I am only using Chrome

Community
  • 1
  • 1
Mike G
  • 33
  • 6

1 Answers1

1

The load event only works with the body element and elements that load in content from outside the HTML document (img, iframe, script, etc.) If you just add a script to the end of the document, it will be executed after your select menu has loaded.

Try putting this before the closing </body> tag:

<script>
  var dropdown = document.querySelector('select');
  dropdown.className = dropdown.options[dropdown.selectedIndex].className;
</script>

If you have multiple select menus, you might want to give each an id attribute and use that to find them; the above code will only affect the first one on the page.

user6939352
  • 457
  • 5
  • 7