Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can Select a Value in a select box with Javascipt

Status
Not open for further replies.

mcbigj

Programmer
Dec 14, 2001
83
0
0
US
Hello,

How can I select a value in a select box in javascript? For instance:

<select>
<option>California</option>
<option>Nevada</option>
</select>

I want javascript to basically add the html function "selected" to the option box based on a query I have. So if "CA" was returned, I'd want the javascript to select California in the dropdown.

Thanks for any help.
 
based on a query you have? so, i assume you're writing this html dynamically?

do this:

Code:
<select name="sel">
  <option selected>California</option>
  <option>Nevada</option>
</select>

*cLFlaVA
----------------------------
[tt]a frickin' twelve-gauge, what do you think?[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
 
No, what I want to happen is the javascript ADD the selected part to the code, OR have the California selected by using the javascript. so the selected will not be in the option box when the page loads, but then javascript gets called which passes a value like "California" and sets the selected property on the sel box accordingly.

??
 

Something like this will work:

Code:
<html>
<head>
	<script type="text/javascript">
	<!--

		function selectItem(itemText) {
			var sel = document.forms[0].elements['sel'];
			for (var loop=0; loop<sel.options.length; loop++) {
				if (sel.options[loop].text == itemText) {
					sel.selectedIndex = loop;
					break;
				}
			}
		}

	//-->
	</script>
</head>

<body onload="selectItem('Nevada');">
	<form>
		<select name="sel">
			<option>California</option>
			<option>Nevada</option>
		</select>
	</form>
</body>
</html>

Hope this helps,
Dan


[tt]D'ya think I got where I am today because I dress like Peter Pan here?[/tt]
[banghead]

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top