我想要做的是允许用户在提交数据时选择是否添加更多文本框。
到目前为止,我有这段代码
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组文本框,用户将无法添加更多文本框。
答案 0 :(得分:2)
要发布到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. */
}
});
答案 1 :(得分:1)
您必须检查add事件中的输入数量。 您使用表单标记将数据传输到服务器和 您还必须使用GET或POST
在表单标记中设置“method”属性<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>