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

How to set "selected" in list box?

Status
Not open for further replies.

JonathanG6SWJ

Programmer
Jan 18, 2005
39
GB
On an asp page that allows the user to edit account details I have a list box showing relationships.

I need to set the selected option to that retrieved from a DB record when I create / present the edit page to the user.

No matter what I try I always seem to select the last item in the list - any clues.

Code:
<%
j0="False"
j1="True"
j2="False"
j3="False"

%>

<select name="Relationship" id="mySelect" >
<option value="0" selected="<%=j0%>"></option>
<option value="1" selected="<%=j1%>">Me</option>
<option value="2" selected="<%=j2%>">Boss</option>
<option value="3" selected="<%=j3%>">Team</option>              
                       
</select>
Regards
Jonathan
 
you muust only set the one you want to SELECTED - not all of them. Your syntax is also slightley wrong:
Code:
<select name="Relationship" id="mySelect" >
<option value="0"></option>
<option value="1">Me</option>
<option value="2" [red]selected[/red]>Boss</option>
<option value="3">Team</option>                           
</select>

Tony
_______________________________________________________________
 
Thanks Tony.
Is there an obvious way I can do this programatically (is that a word!) In other words dynamically build the list box and define which one is selected depending on details from a record from a DB.

Jonathan
 
Something like this would do it...
Code:
<%
If NOT objRS.EOF Then
  While NOT objRS.EOF
    If CInt(objRS("id")) = [red]2[/red] Then
      strSelected = " selected"
    Else
      strSelected = ""
    End If

    Response.Write "<option value='" & objRS("id") & "'" & strSelected & ">" & objRS("Relationship") & "</option>" & vbcrlf

    objRS.MoveNext
  Wend
Else
'no records found
End If
%>
Where I have used [red]2[/red] you would need to replace that with your desired value - probably from a Request.Form variable maybe. If you do use a Request variable then remember to CInt() it first before comparing it to the recordset value.

Tony
_______________________________________________________________
 
You should use:

Code:
<option value="2" selected="selected">Boss</option>
 
JontyMC is right. If you want your site to be XHTML 1.0 compliant then you need to use [red]selected="selected"[/red] instead of just [red]selected[/red]

Tony
_______________________________________________________________
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top