代码之家  ›  专栏  ›  技术社区  ›  itsaboutcode

经典ASP表单中输入字段的数量可变

  •  3
  • itsaboutcode  · 技术社区  · 16 年前

    我有一个退房表,产品的数量可以是“n”。那么我如何知道表单中有多少个输入字段并从中获取输入呢?

    1 回复  |  直到 14 年前
        1
  •  10
  •   BradBrening    16 年前

    如果是一组单个控件(比如代表项的可变数量的复选框),那么解决方案非常简单。对于您的复选框:

    <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
    

    然后在ASP中,可以执行以下操作:

    <%
      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
    %>
    

    事实上,这种方法适用于任何数量的同名控件。如果是1-n个名为“FavoriteColor”的文本框,您可以 For Each 以相同的方式通过每个值。没有用户输入的文本框将不会被传递。

    现在,如果您的签出窗体包含每个项的一组输入控件,则可以通过仔细命名其他控件来构建该方法:

    <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>
    

    现在,在服务器上,您可以这样解析数据:

    <%
      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
    %>
    

    您将能够以这种方式对每组选定项执行验证和其他逻辑。

    推荐文章