How to set the selected combo option with Javascript

L

lister

Hi all,

If have the following combo:

<select name="combo">
<option value="a">One</option>
<option value="b">Two</option>
<option value="c">Three</option>
</select>

How can I programmatically set the selected option, given that I know
the value of "value" (ie say "b")?

I know how to get hold of the combo etc in script, it's just the actual
setting of the value :-/

Many thanks,
Lister
 
V

VK

lister said:
Hi all,

If have the following combo:

<select name="combo">
<option value="a">One</option>
<option value="b">Two</option>
<option value="c">Three</option>
</select>

How can I programmatically set the selected option, given that I know
the value of "value" (ie say "b")?

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
</head>

<body onload="
var val = 'b';
var sel = document.forms[0].elements['combo'];
var len = sel.options.length;
for (var i=0; i<len; ++i) {
if (sel.options.value == val) {
sel.options.selected = true;
break;
}
}
">
<form>
<select name="combo" size="3">
<option value="a">One</option>
<option value="b">Two</option>
<option value="c">Three</option>
</select>
</form>
</body>
</html>
 
B

Bart Van der Donck

lister said:
If have the following combo:

<select name="combo">
<option value="a">One</option>
<option value="b">Two</option>
<option value="c">Three</option>
</select>

How can I programmatically set the selected option, given that I know
the value of "value" (ie say "b")?

document.forms[0].combo.value = 'b'
 
L

lister

VK said:
var val = 'b';
var sel = document.forms[0].elements['combo'];
var len = sel.options.length;
for (var i=0; i<len; ++i) {
if (sel.options.value == val) {
sel.options.selected = true;
break;
}
}


Brilliant!
Thanks a million.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,225
Latest member
Top Crypto Podcasts

Latest Threads

Top