使用JQUERY动态生成表单文本框

创建div这类普通标签和创建表单input、textarea有所区别:表单元素重点需要动态设置name属性,后端才能接收提交的数据。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm24.aspx.cs" Inherits="WebApplication1.WebForm24" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
    <script>
        function addinput()
        {
            $("#files").append($("<p><input type='text' name='files'/></p>"));
        }
    </script>
</head>
<body>
    <form action="WebForm24.aspx" method="post">
        <input type="button" value="+" onclick="addinput()" />
        <div id="files"></div>
        <input type="submit" value="确定" />
    </form>
</body>
</html>
Code language: HTML, XML (xml)

说明:

  1. 点击+按钮执行addinput(),动态追加带name属性的文本框到#files容器。
  2. 所有动态生成input的name都为files,提交表单时后端可以一次性拿到全部文本框的值。
  3. 后端接收数据属于拓展内容,本节课重点掌握前端动态创建表单元素。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注