PDA

View Full Version : for loop w/ select box


chrismiceli
11-17-2002, 04:56 AM
i have a select box that i am trying to generate dynamically here is my code, it works but it generates and error

i = 0
document.user.box.length = 4
for (i=0; i <= document.user.box.length; ++i) {
document.user.box[i].text = i;
}

i get this error in mozilla
Error: document.user.box[i] has no properties
Source File: file:///home/cpu/documents/scripts/rpg.js
Line: 5
what is wrong, it is not recognized the i as a variable in that line, why??

RadarBob
11-17-2002, 05:26 AM
If you have this select object:

<select name="user" onchange="doSomething(this);>
<option value="whatever">whatever</option
. . .
</select>


You reference the options like this:

function doSomething(theSelect) {
var thisOption;

for (var i=0; i<theSelect.options.length; i++) {
thisOption = theSelect.options[i].text;
}
}


if you don't pass the select as a parameter in a function call, you can reference it "from the top" like this:

document.formname.selectname.options.length

chrismiceli
11-17-2002, 06:15 AM
i have a select box like this that i am trying to fill dynamically

<select name="box">
<option></option>
</select>

the name of my form is user. the code i posted at the beginning works, just generates an error.

Algorithm
11-17-2002, 07:23 AM
The code works because Javascript allows you to dynamically assign properties to existing objects. document.user.box.length has no meaning outside of your function. You're looking for document.user.box.options.length.

Similarily, when accessing a specific option, you'll want to use document.user.box.options[i].

chrismiceli
11-17-2002, 03:59 PM
thanx, i was forgetting the .options property of the select box.