PDA

View Full Version : how to tell a select object which option to highlight?


smanning
11-18-2002, 08:32 PM
I'm trying to tell a select object dynamically which option is selected. How do you do that?

This is what I was trying to do:

document.forms.mySelect.selectedIndex=3;

What's wrong with this picture?

Thanks.

Steve

beetle
11-18-2002, 09:11 PM
It's all in your reference. forms is a document collection, so you are trying to set the selectedIndex property of the 'mySelect' form on the page (which I suspect doesn't exist).

Maybe...

document.forms[0].mySelect

or

document.formName.mySelect

Mr J
11-19-2002, 10:17 PM
Maybe?




document.formname.selectname.options.selectedIndex = document.formname.selectname.options[document.formname.selectname.selectedIndex].value

glenngv
11-20-2002, 01:17 AM
No.

It's:

document.formNameHere.mySelect.selectedIndex = 3;

beetle is correct, he just didn't explicitly showed the exact solution.

whammy
11-20-2002, 01:23 AM
Actually, that won't work with XHTML (since you can't "name" a form, you have to use "id")...

I would think that you'd be better off using forms[0] (or whatever form you're referencing if you have more than one form on the page). i.e.:

document.forms[0].mySelect.selectedIndex = 3;

However, with XHTML I have also found that to be problematic, since javascript still does not seem to recognize forms without a "name".

Probably your best bet is to pass the form object to a function... but in order to do that I'd have to see the code you're using (my post assumes you're worried about XHTML compatibility - if you don't care, then ignore this post. ;)).

If someone knows a hack around this method (i.e. using (this.form) or (this) when referencing the form in XHTML, and passing that value to a function), please let me know... although I've usually found the scripts once modified to be more efficient and elegant in the long run when coding this way. But it can be a pain...

beetle
11-20-2002, 03:15 AM
The forms collection with the lookup operator [] can receive the (1) Form's index in the collection (2) Form's name (3) Form's id. So, it's perfectly valid to say

document.forms['formName']

With XHTML (I just tested it to be sure ;))

whammy
11-20-2002, 03:16 AM
Hmm.. must have been something else I was doing wrong then - I was just able to use document.forms[0] with a simple test...

I will try ['formname'] and see how that works if I run into problems with it in the future. ;)