homepage Welcome to WebmasterWorld Guest from 54.197.183.230
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

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

5+ Year Member



 
Msg#: 3748219 posted 8:08 pm on Sep 19, 2008 (gmt 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?

Thanks,

 

babushka

5+ Year Member



 
Msg#: 3748219 posted 8:24 pm on Sep 19, 2008 (gmt 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;
}
}

Trace

5+ Year Member



 
Msg#: 3748219 posted 8:27 pm on Sep 19, 2008 (gmt 0)

Try this instead of that whole po thing;

listBox[listBox.selectedIndex].value

Fotiman

WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member



 
Msg#: 3748219 posted 8:54 pm on Sep 19, 2008 (gmt 0)


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;
}
}

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved