Welcome to WebmasterWorld Guest from

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

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

Junior Member

10+ Year Member

joined:Oct 1, 2005
votes: 0

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?


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

Junior Member

10+ Year Member

joined:Oct 1, 2005
votes: 0

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;

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

Preferred Member

10+ Year Member

joined:July 5, 2005
votes: 0

Try this instead of that whole po thing;


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

Senior Member from US 

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

joined:Oct 17, 2005
votes: 14

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;

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members