Welcome to WebmasterWorld Guest from 54.147.44.93

Forum Moderators: open

Message Too Old, No Replies

get index of option of a drop down list box for a give value

option list box

     

babushka

8:08 pm on Sep 19, 2008 (gmt 0)

5+ Year Member



I am so not understanding this javascript/dom.

I have list box: mylistbox

I can get the listbox:

var listBox = document.getElementById("mylistbox");

but now I want to get the index of an option based on the value so I can select it dynamically.

So say I dynamically set the options to:

<option value="14">apples</option>
<option value="22">oranges</option>

BTW, javascript var myvar = 22;

Now I want to select the value "22" in the options and have that show in the list box the one that is selected.

I tried:

var po = listBox.getElementsByTagName("option");
var myvalue = po[myvar].value;

Doesn't work.

And I can't seem to dump 'po' because all I get is [object].

And is there a solid book that thoroughly covers issues like this?

Thanks,

babushka

8:24 pm on Sep 19, 2008 (gmt 0)

5+ Year Member



I guess I have to loop through it all.

for (var x=0; x < mylen;x++){
if ( po(x).value == myvar) {
listBox.options[x].selected = true;
}
}

Trace

8:27 pm on Sep 19, 2008 (gmt 0)

10+ Year Member



Try this instead of that whole po thing;

listBox[listBox.selectedIndex].value

Fotiman

8:54 pm on Sep 19, 2008 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month




I guess I have to loop through it all.

Yes, that is the correct way to do it because you're searching an array of option elements for the one option that has a value attribute that matches a value you're searching for. But you don't need to do listBox.getElementsByTagName("option"). listBox has an "options" collection that contains all of the options already, so you could do:

for (var x = 0; x < mylen; x++) {
if (listBox.options[x].value == myvar) {
listBox.options[x].selected = true;
}
}
 

Featured Threads

Hot Threads This Week

Hot Threads This Month