[英]jquery append input field and post
$('#submit').click(function(){
$.post(
'/foo.php',{
name:myform.name.value,
interest:myform.interest.value,
interest2:myform.interest2.value...
}
});
<input type="button" value="Add more interest" />
我有一个形式使用jQuery的职位。 有一个按钮可以附加更多输入类型的文本。
我的问题
1当用户单击并在$.post(...
一侧添加更多输入字段时,如何添加更多脚本,以便可以将其发布到下一页?
2在我的PHP页面
if(isset($_POST['interest1'], $_POST['interest2']...)){}
我怎么知道用户添加了多少个额外的输入字段?
3如何限制用户可以追加的最多3个输入字段?
您是否在发帖请求中手动设置表单字段? 坏主意,最好使用jQuery的serialize方法:
$.post("/foo.php", $("#myForm" ).serialize() );
第二个问题:在表单元素上使用数组命名:
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
这样,您就可以在post数组中获得一个数组,并可以像这样使用它:
foreach ($_POST['interest'] as $interest) {
doStuff();
}
对于第三个问题,我假设您编写了一个JS方法,该方法向表单添加了输入字段? 如果是这样,您可以通过以下方式实施限制:
window.formFieldCount = 1;
function addFormField() {
if (window.formFieldCount >= 3) {
alert('You can only add three interests!');
return false;
}
// Do your form magic here
window.formFieldCount++;
}
HTML :
<form name="some_name">
<div id="interests">
<input type="text" name="interests[]" />
</div>
<input id="more-interests" type="button" value="Add more interest" />
<input id="submit" type="button" value="Submit" />
</form>
Javascript :
$(document).ready(function(){
var maximumNumberOfInterests = 3;
$('#more-interests').click(function(e){
if ($("input[name='interests[]']").size() < maximumNumberOfInterests) {
$('#interests').append('<input type="text" name="interests[]" />');
} else {
alert('The maximum number of interests has been reached!');
}
});
$('#submit').click(function(){
$.post('/foo.php', $('form').serialize());
});
});
PHP的 :
if (count($_POST['interests'])) {
foreach ($_POST['interests'] as $interest) {
echo $interest;
}
}
q2。 你可以这样改变形式:
静态输入
<input name='static[something]'>
<input name='static[somebody]'>
<input name='static[etc]'>
和动态生成的输入
<input name='dynamic[]'>
<input name='dynamic[]'>
<input name='dynamic[]'>
的PHP
if (isset($_POST['dynamic']))
{
foreach ($_POST['dynamic'] as $key => $value)
{
/* do some shit with dynamic inputs */
}
}
提交表格前请使用前置功能
喜欢
$("#myForm").prepend("<input type=\"text\" name=\"interest"+counter+"\"").submit(function(){
console.log($("#myForm" ).serializeArray())
$.post(Event.target.action, $(Event.target).serializeArray(), function(data){
// your code here
})
return false;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.