0

Say I have a select input with 10 options and the id "myselect". How can I, on page load or basically as early as possible so that it seems as if it loaded this way, check which option is selected in "myselect" and add a css class to the parent, parent div that the select is in?

The second part of this question is, if you change the select after the page loads what is the best way to change the css class accordingly? Would it be best to just add a second javascript bit that uses something like onclick rather than onload?

BRAINBUZZ media
  • 494
  • 3
  • 9
  • 25
  • onload nothing is selected. Or do you have something special? – Bergi Aug 01 '12 at 11:49
  • [jsfiddle.net](http://jsfiddle.net/) is there for testing things like this. When you play around there and show us a link we can help you out better – bart s Aug 01 '12 at 11:51
  • It is ajax so the settings from previously are saved on refresh. It is a bunch of files working together with ajax. Isn't this fairly straightforward to grab the id of something and see what is selected? – BRAINBUZZ media Aug 01 '12 at 11:59
  • take a look [here](http://stackoverflow.com/a/496126/474535) – bart s Aug 01 '12 at 12:02
  • Uh, you've got code for this - show it to us! If options are selected by code, we will need to hook on that. – Bergi Aug 01 '12 at 12:13

1 Answers1

0

The best way to hook into something as soon as it has loaded is to use an inline JavaScript block immediately after the HTML element. It's a lot less elegant than using document.ready, but it's sure to work. Something like this:

<select name="s1" id="S1">...<.select>
<script type="text/javascript">
var sel = document.forms[0].S1;
var ind = sel.selectedIndex; <-- this will tell you which is selected
if(ind==3) {
    document.getElementById("S1").parentNode.setAttribute("className", "active")
}
</script>

For the second part, you want to hook up the "onchange" event.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176