开发者

Dynamic checkboxes in asp

How can I get the values from a dynamically created checkbox group using asp classic? It seems that when I select my checkboxes and hit submit there are no values passed on the first click, but when开发者_JS百科 I click it again they appear.

How can I fix this without hard-coding the checkboxes on the form?


One way I did it was to contain a comma-separated list of checkbox IDs, and each time the checkbox was clicked, add the ID to the list via javascript. When the page submits, I add that list as a request variable. Loading the page, I determine if that checkbox ID is already in the list, and if it is, I set its checked attribute to true.

I did this forever ago, so please excuse me if it's not clear.


Here you go

<% OPTION EXPLICIT %>
<% 

sub echo(X)
    response.write x
end sub

echo "<form method='post'>"
dim i
for i = 1 to 5
    echo "<input type='checkbox' name='checkboxes' value=" & i & " />" & i & "<br />"
next
echo  "<input type='submit' value='Show me the checkboxes'>"
echo "</form>"

echo "<br />Selected items: " & request("checkboxes")


%>


I had another control on the page (drop-down box) and I stuck an onchange event on it. The onchange event would trigger a button click for the forms submit button. This simulated the first click. For some reason it took two clicks to bind the form with the checkbox values, so the onchange simulated the first click and the regular button is the second.


Since i assume you would like to maintain the checkbox state during postback i'm adding my version of the dynamic checkbox generating code:

<%
    Dim checkboxes
    Dim i
    checkboxes = Array(1, 2, 3, 4)

    For i = 1 To (UBound(checkboxes) + 1)
        Response.Write "<input type=""checkbox"" name=""checkGroup"" value=""" & i & """"

        If (UBound(Filter(Request.Form("checkGroup"), i, True, 1)) > -1) Then
            Response.Write " checked"
        End If

        Response.Write " />"
    Next
%>

A second way to do this would be

<%
    Dim checkboxes
    Dim boxeschecked
    Dim i
    checkboxes = Array(1, 2, 3, 4)
    boxeschecked = "," & Join(Request.Form("checkGroup"), ",") & ","

    For i = 1 To (UBound(checkboxes) + 1)
        Response.Write "<input type=""checkbox"" name=""checkGroup"" value=""" & i & """"

        If Instr(boxeschecked, ("," & i & ",")) > 0 Then
            Response.Write " checked"
        End If

        Response.Write " />"
    Next
%>

I recall that using Instr() did perform better than other methods - better than looping over the array in any case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜