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!

Passing pre-selected values to a pulldown menu

Status
Not open for further replies.

FreeBASE

Programmer
May 3, 2002
39
US
Lets say I have a database.. I also have an HTML form to add/edit the database.. If a user already has data in the database then the form should already be filled out with the data on load. This means the text field values, radio button values, and of course pulldown menu's.

EXAMPLE::

If the database value of the pulldown menu for "country" is "AK" then the pulldown will have "Arkansas" already selected for the user.

If the database value of the pulldown menu for "country" is "AL" then the pulldown will have "Alabama" already selected for the user.

If there is no value in the database for "country" then the pulldown menu will not have any pre-selected values.

So basically what i am trying to do is create a javascript that can accomplish this. I am using a template system to fill out the javascript values and got it to work with radio buttons and text fields. I just can get it to work with pulldowns.

This is the form I am using:

<body onload=FillOutOptions()

<form name=theForm>
<select name=country>
<option value=&quot;&quot;>
<option value=&quot;AL&quot;>Alabama
<option value=&quot;AK&quot;>Alaska
<option value=&quot;AS&quot;>Am. Samoa
</select>

This is what currently works..

<script language=&quot;javascript&quot;>
<!--//
function FillOutOptions() {
document.theForm.gender[<%TEMPLATE VALUE FOR GENDER%>].checked = true; // This selects the radio button
document.theForm.name.value = &quot;<%TEMPLATE VALUE FOR NAME%>&quot;; // This fills in the name field

}
//-->
</script>

Just need it to work with pulldowns...
 
Try this:

----
Code:
for (i=0;i<document.theForm.country.length;i++){
   	if (document.theForm.country.options[i].value==<%TEMPLATE VALUE FOR COUNTRY%>){
		document.theForm.country.options[i].selected= true
		i=document.theForm.country.length
		}
	}
---------

What it's doing:
1. Loop through all the <option>s in the drop-down list.
2. Check if the current option's value is equal to the COUNTRY value stored in the database.
3. When you find the right option based on the value, set the &quot;selected&quot; property to true, and exit the loop.

Note: The &quot;selected&quot; value in the drop down will show in the drop-down box, but will not be &quot;highlighted&quot;. It will be used as the value when the form is submitted.

Hope this helps. Ciao, K
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top