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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

set a dropdown value

Status
Not open for further replies.

craigward

Programmer
Nov 13, 2007
230
GB






Hi There, I have a dropdown field called county that i want to set to a value of when a link is clicked. See my example code. Any input would be great thanks.

The error i get is document.forms[o].county is null or not an object.

Code:
<html>

<head>


<script language="JavaScript">

function setfield(){

document.forms[0].county.value ="TEST"

}

</script>
</head>
<body>

<a href="#" onClick="setfield()">set dropdown</a>


<select name="county" id="county">
<option value"not set">not set</option>
<option value" still not set">still not set</option>
</select>

</body>
</html>












 
Sorry, the code here was something i mocked up from a live system and i missed out the form out... The error is gone though but it set the value to blank. Could you run your eye over it?

Thanks

Code:
<html>

<head>


<script language="JavaScript">

function setfield(){

document.forms[0].county.value ="TEST"

}

</script>
</head>
<body>

<a href="#" onClick="setfield()">set dropdown</a>

<form name=form1>
<select name="county" id="county">
<option value"not set">not set</option>
<option value" still not set">still not set</option>
</select>
</form>
</body>
</html>
 
Technically you can't set the value of dropdown like that.

You can make one of the options it has be the selected one, but you can't set the value and then have it be submitted.

You can also set one of the existing option's value to something, and then set it as the selected option, but you can't directly set the value of the dropdown as that is merely a JS reference which does not get submitted with the form.

Code:
document.forms[0].county.options[x].selected-"selected":

or even


document.forms[0].county.options[x].value="TEST";
document.forms[0].county.options[x].selected="selected";

Where x is any value between 0 and the number of options your dropdown has, minus one. If your dropdown has 5 options x can be 0 through 4.




----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top