Dynamically Setting the selected option in a select box

How would I use JS to select the <option> dynamically?

Basically I have a class (java) that dynamically pulls a list from a database, puts it in <option> tags and spits it back to my jsp file, so I need to set which one is selected after they’ve been displayed, but need to do it without touching the html, cause i can’t.

This make sense?

basically after the select is created i want to set the selected option.

Thanks in advance.

document.forms[‘formName’].elements[‘elementName’].selectedIndex = someInteger;

That make sense?

Yes indeedy, trying it now…

Hrm… bleh.
I need to do it based on an alpha-numeric ID. (ex: A010)

Can it match values?

This is what the <option> looks like:

<option value="A0145">COMM: ERROR CORRECTION FACILITY</option>

Sure


function selectOptionByValue( elem, value )
{
var opt, i = 0;
while( opt = elem.options[i++] )
{
if ( opt.value == value )
{
opt.selected = true;
return;
}
}
}

Just pass it a reference to the select element, and the value


selectOptionByValue( document.forms['[i]formName[/i]'].elements['[i]elementName[/i]'], '[font=Courier]A0145' [/font]);

hrmm… ok, that looks like what I want.
But where would I call it?

Also, could i call it before the form etc?

Bleh, sorry for the 3 replies, but I really have no idea how to call a JS function outside of an onClick, onLoad etc events.

I just want to call this mid-page, since the page’s content is dynamic and I’d get JS errors by calling it onLoad if the form/element didn’t exist (which it won’t half the time).

To run it mid page, just insert a script element


<script type="text/javascript">
	selectOptionByValue( document.forms['[i]formName[/i]'].elements['[i]elementName[/i]'], '[font=Courier]A0145' [/font]);
</script>

And keep the function in the <head> or a linked .js file.

Also, you could build fault tolerance and exception handling into the function, if you wanted.

Hrm… i get an error if i call it before the form is defined etc.
So I guess i have to call it after the select and form?

Ok, it’s working for 1 of them.
But I get an error that A0371 is undefined, but here’s the option for it in the list:

<option value="A0371">RAM: APP (APP NAME)</option>

hrm… nevermind, I made a bad call (no pun intended )
I was doing this:
[color=#000000]

<script type='text/javascript'>selectOptionByValue(document.forms['EditApp'].elements['RPTG_APPL_ID'], A0371); </script>
// When i should've done this:
<script type='text/javascript'>selectOptionByValue(document.forms['EditApp'].elements['RPTG_APPL_ID'], 'A0371'); </script>

[/color]
Thanks for your help beetle! :slight_smile:

Hehe, ya, can’t forget those string delimiters!

You’re welcome :smiley: