Multiple selections in dropdown

I have a comma delimited list of Id's called "myIDS". It contains lists such as:

I create an ASP dropdown list such as:

<select name="shipList" class="input" size="6" multiple>
<option value="4" >Name1</option>
<option value="11" >Name2</option>
<option value="30" >Name3</option>
<option value="34" >Name4</option>
<option value="26" >Name5</option>
<option value="8" >Name6</option>
<option value="13" >Name7</option>

I need to set the options in the dropdown to "Selected" if the value is in the comma delimited list = the values in the list. Keep in mind, the dropdown is generated dynamically from a DB.

Any ideas?
Who is Participating?
Om PrakashCommented:
dim myIDS
myIDS = "4,11,30,"

In this case 4 will be selectetd but 14 and 41 will not

<option value="4" <% IF InStr(myIDS,"4") > 0 THEN response.write " selected" %>>Name4</option>
<option value="41" <% IF InStr(myIDS,"41") > 0 THEN response.write " selected" %>>Name41</option>
<option value="14" <% IF InStr(myIDS,"14") > 0 THEN response.write " selected" %>>Name14</option>
Om PrakashCommented:
you can use instr to do this
<option value="4" <% IF InStr(myIDS,"4") > 0 THEN response.write " selected" %>>Name1</option>
<option value="11" <% IF InStr(myIDS,"11") > 0 THEN response.write " selected" %>>Name2</option>

similarly you can add for other options

AS_SSURAuthor Commented:
I tried "inStr" but 4 and 14 both have a "4" in the Str.

1. create an array from the string MyIDS

arrMyIds = Split(myIDS, ",")

Use attached function IsElementOfArray() to check if it's there. Oh, and I have a standard function IIF(), which is quite useful (and present in most languages, but not in VBScript)

<option value="4" <%=IIF(IsElementOfArray("4", arrMyIds, "selected")%>>Name4</option>
<option value="14" <%=IIF(IsElementOfArray("14", arrMyIds, "selected")%>>Name4</option>

Note that it makes a different if "4" is a String or a Number, because "4" = 4 returns False.


Alternatively, if you want to use the Instr() method as above, use it as this:

' encapsulate thew myIDS string with comma's
myIDS = "," & myIDS & ","

' now search for ",4," or ",14," etc

<option value="4" <% IF InStr(myIDS,",4,") > 0 THEN response.write " selected" %>>Name4</option>

Function IsElementOfArray(ByVal v, ByVal a)
    Dim e
    IsElementOfArray = False
    If Not IsArray(a) Then Exit Function
    For Each e In a
        If v = e Then IsElementOfArray = True: Exit For
End Function

Function IIf(bCondition, TrueValue, FalseValue)
    IIf = FalseValue
    If bCondition Then IIf = TrueValue
End Function

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.