添加或删除文本框,然后使用 PHP 或 jquery 获取它们的值


Add or Delete Textbox Then Get Their Value Using PHP or Jquery

我想做的是允许用户在提交数据时选择是否添加更多文本框。

到目前为止,我有这个代码

http://code.jquery.com/jquery-1.5.1.js

这是我得到的代码。

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">

  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <style type='text/css'>
    .Delete{color:#ff0000;}
.Add {color:green;}
.Retrieve{color:blue;} 
  </style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function(){
    $('.Delete').live('click',function(e){
    $(this).parent().remove();
    });
    $('.Add').live('click',function(e){
        $('.Option:last').after($('.Option:last').clone());
    });
    $('.Retrieve').live('click',function(e){
        $('.Option input').each(function(i,e){
        alert($(e).val()); //Alerts all values individually
        });
    });
});
});//]]>  
</script>
</head>
<body>
  <div class='Option'>
    <input type='text' name='txtTest'/>
    <input type='text' name='txtTest'/>
    <input type='text' name='txtTest'/>
    <span class='Delete'>Delete</span></div>
    <br/><br/>
    <span class='Add'>Add Option</span>
    <br/><br/>
    <span class='Retrieve'>Retrieve Values</span> 
</body>
</html>

该代码允许我添加更多文本框并删除它们,但我的问题是我正在尝试使用 PHP GET 或 PHP POST 获取这些文本框的值,如果可能的话,设置一些限制,也许在添加 5 组文本框后,用户将无法添加更多。

为了发布到 PHP,只需将 HTML 包装在 form 元素中:

<form method="GET" action="myPage.php">
    <div class='Option'>
        <input type='text' name='txtTest'/>
        <input type='text' name='txtTest'/>
        ...
    </div>
</form>

然后,要限制可以添加的.Option元素的数量,只需声明一个全局变量来计算.Option元素的数量:

var optionCount = 1;
$('.Delete').live('click',function(e){
    $(this).parent().remove();
    optionCount--; /* Decrease optionCount. */
});
$('.Add').live('click',function(e){
    if (optionCount < 5) { /* Only if optionCount is less than 5... */
        $('.Option:last').after($('.Option:last').clone());
        optionCount++; /* Increase optionCount. */
    }
});

您必须检查 add 事件中的输入数。您使用表单标记将数据传输到服务器和您还必须使用 GET 或 POST 在表单标签中设置"方法"属性

    <html>
    <body>
    <head> 
<script type='text/javascript'> $(function(){
 $('.Add').live('click',function(e){
       if($('.option input').length < 5)
       {
          $('.Option:last').after($('.Option input:last').val('').clone());
       }
          // Other code
          // ...
 }
    });
</script>
</head>
    <form action="welcome.php" method="post">
    <input type='text' name='txtTest'/><br>
    <input type='text' name='txtTest'/><br>
    <input type="submit">
    </form>
    </body>
    </html>