Click to See Complete Forum and Search --> : accessing selectedIndex


MrGronkle
12-10-2002, 12:32 PM
It seems this should be simple, but ...
I have a select list containing a list of products. The select is the first element in the only form in the document. I want the selected product name to appear a couple of places in some boiler plate text at the bottom of the form. I tried creating a little function that I placed in the <head> </head> that would document.write the product name when called from the appropriate place(s) in the boiler plate. Problem is, the function is able to see and write out document.forms[0].elements[0].options.length ok. It is able to see and write out document.forms[0].elements[0].options[number].value ok if I supply an actual numeral. However, the function cannot see document.forms[0].elements[0].options.selectedIndex although it seems like it should be able to. No matter what option is selected from the list, the selectedIndex is always given as "0". Is this a scope issue? This seems like a trivial thing that folks would want to do all the time, so the answer, I assume, should be simple. Any hints??

MrGronkle
12-10-2002, 06:30 PM
Unfortunately, I tried the syntax Mr. Clark suggested at the beginning of this undertaking (and again right now) and it does not work either. Mr. Clark's suggestion is indeed consistent with the usage in Flanagan's JavaScript (O'Reilly) page 672. I tried the syntax shown in my original posting based on the vague hope that select.options.selectedIndex would be synonymous with select.selectedIndex as is supposed to be the case with select.length and select.options.length (Flanagan p. 670). If all else fails, I will post a bare-bones version of the code.
thnx

MrGronkle
12-12-2002, 12:53 AM
This is what finally worked for this beast:
var myvar=document.forms[0].elements[0].options[document.forms[0].elements[0].selectedIndex].value;

It turns out that getting the value for selectedIndex needed to recover the value of the selected option in the list requires that one designate the particular element of the array with the entire term "document.forms[0].elements[0].selectedIndex" rather than simply with "selectedIndex"


Thanks to Dave Clark for the explanation and to my son who quickly spotted the flaw in my logic.