Page 1 of 1

selectedIndex in an onload function

Posted: Wed Jul 14, 2010 8:42 am
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?

Re: selectedIndex in an onload function

Posted: Wed Jul 14, 2010 1:48 pm
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">

Re: selectedIndex in an onload function

Posted: Thu Jul 15, 2010 3:56 am
by skylark2
Thank you! Works great and explanation makes sense. I am starting to get my brain wrapped round this...