selectedIndex in an onload function

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
skylark2
Forum Commoner
Posts: 32
Joined: Wed Jun 16, 2010 6:00 am

selectedIndex in an onload function

Post by skylark2 »

Javascript newbie here, rather confused...

I'm converting an old executable program into a web-based program, and have a dialog where various options depend on other options. I can set two select lists' selected indexes to the be the same based on an onchange. This works fine.

What I don't seem to be able to do is set selectedIndex in the javascript function which is called in onload. I can see the function gets called - it'll pop up an alert perfectly happily. But the selectedIndex line after it is simply ignored. (It was more complex than this - it was reading the value from somewhere else - but it fails no matter how simple I make it).

Code: Select all

function load(form)
{
  form.mv.options.selectedIndex=1;
}
and then

Code: Select all

<body onload='load(this.form)'>
I missed something really basic, right? Am I not allowed to use selectedIndex in an onload function? Or can someone point me at a five line example which works to start from?
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: selectedIndex in an onload function

Post by kaszu »

"this" refers to document.body, and document.body doesn't have property "form" and you can't access children like that. Instead try using ID

Code: Select all

<body onload="load(document.getElementById('myform'))">
...
<form id="myform">
skylark2
Forum Commoner
Posts: 32
Joined: Wed Jun 16, 2010 6:00 am

Re: selectedIndex in an onload function

Post by skylark2 »

Thank you! Works great and explanation makes sense. I am starting to get my brain wrapped round this...
Post Reply