views:

136

answers:

1

Hi,

I have a check out form where number of products can be "n". So how i can know how many input fields are in the form and take input from it?

Thanks

+5  A: 

If it's a group of single controls - say a variable number of checkboxes representing items - the solution is pretty straightforward. For your checkboxes:

<input type="checkbox" name="ProductID" value="1" />Product #1<br />
<input type="checkbox" name="ProductID" value="2" />Product #2<br />
<input type="checkbox" name="ProductID" value="3" />Product #3

Then in your ASP, you could do this:

<%
  Dim intID

  For Each intID In Request.Form("ProductID")
    ' intID now represents a selected product ID.  Insert into DB
    ' or whatever your process is.  Note that only the "checked" values
    ' will be passed to the server.
  Next
%>

In fact, this approach will work for any number of controls with the same name. If it were 1 - n number of textboxes with the name "FavoriteColor", you could For Each through each value in the same manner. Textboxes with no user input would not be passed.

Now, if your checkout form contains a group of input controls per item, you can build on that approach by carefully naming your other controls:

<div>
<input type="checkbox" name="ProductID" value="1" />Product #1<br />
<input type="textbox" name="Product1_Quantity">
<input type="textbox" name="Product1_Color">
</div>

<div>
<input type="checkbox" name="ProductID" value="2" />Product #2<br />
<input type="textbox" name="Product2_Quantity">
<input type="textbox" name="Product2_Color">
</div>

<div>
<input type="checkbox" name="ProductID" value="3" />Product #3
<input type="textbox" name="Product3_Quantity">
<input type="textbox" name="Product3_Color">
</div>

Now, again, on the server you could parse the data in this way:

<%
  Dim intID
  Dim intQuantity
  Dim strColor

  For Each intID In Request.Form("ProductID")
    ' this is a selected item
    intQuantity = Request.Form("Product" & intID & "_Quantity")
    strColor = Request.Form("Product" & intID & "_Color")
  Next
%>

You'd be able to perform validation and other logic on each group of selected items in this manner.

BradBrening