Click to See Complete Forum and Search --> : how to dynamically set the selected option for a select tag.


yu169409
09-23-2003, 08:22 AM
hi there
i need to dynamically set the selected option for a select tag. i have a variable that contains a value got from DB, and it is one of the options in a select tag. how can i populate the option tags so that this value is selected. if u have sample, it will be much better to understand, thanks.

Charles
09-23-2003, 08:27 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>

<script type="text/javascript">
<!--
onload=function () {document.forms[0].elements[0][1].selected = true}
// -->
</script>

<form action="">
<div>
<select>
<option>Fee</option>
<option>Fie</option>
<option>Foe</option>
<option>Fum</option>
</div>
</form>

But it will not work for the 13% of users who do not use JavaScript. If this is important you will need to use a server side method.

Khalid Ali
09-23-2003, 08:36 AM
Originally posted by Charles

onload=function () {document.forms[0].elements[0][1].selected = true}


its presumed that you have only one form on the page as well as one select box.if you add any additional items in the page you uwill need to increment the relative array accordingly....or just assign your form and select the id attributes( or may be a name attribute)

yu169409
09-23-2003, 08:51 AM
thanks for the help and sample code. but how would i be able to check the value i got from database and use that to determine which is selected? i suppose i need server side method to populate the options.

Charles
09-23-2003, 08:54 AM
Originally posted by yu169409
thanks for the help and sample code. but how would i be able to check the value i got from database and use that to determine which is selected? i suppose i need server side method to populate the options. Yes, and while you are at it you can use the script to set the option as selected using HTML. Using JavaScript for this is icky.

Webskater
09-23-2003, 10:09 AM
This may not be appropriate but it might give you the idea. Below is an example of server side asp code setting the option to be selected when the value of ThisPageValue equals the value of the value of the name/value pairs returned by the recordset as you loop through it. During the loop, if the values match "selected" is written in the option tag.
<%
While NOT RS.EOF
isSelected = ""
IF ThisPageValue = RS("Value") THEN isSelected = " selected"
Response.Write "<option value=" & RS("Value") & isSelected & ">" & RS("Name") & "</option>"
RS.MoveNext
Wend
%>

yu169409
09-24-2003, 06:50 PM
thanks a lot.