jQuery追加输入字段并发布 [英] 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帖子的表单.有一个按钮可以附加更多输入类型的文本.
I have a form use jquery post. There is a button can append more input type text.
我的问题
1,当用户单击并附加更多输入字段时,如何在$.post(...
边添加更多脚本,以便将其发布到下一页?
1 when user click and append more input field, in side of $.post(...
how can I add more script, so I can post it to next page?
2在我的php页面中
2 in my php page
if(isset($_POST['interest1'], $_POST['interest2']...)){}
我怎么知道用户添加了多少个额外的输入字段?
how can I know how many extra input fields user has added?
3如何限制用户可以追加的最多3个输入字段?
3 how can I limit maximum 3 input fields user can append?
推荐答案
您是否在发布请求中手动设置表单字段? 坏主意,最好使用jQuery的serialize方法:
Are you setting form fields manually in your post request? Bad idea, you'd be better of using jQuery's serialize method:
$.post("/foo.php", $("#myForm" ).serialize() );
第二个问题:在表单元素上使用数组命名:
For your second question: use array naming on your form elements:
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
<input type="text" name="interest[]">
这样,您就可以在post数组中获得一个数组,并且可以像这样使用它:
This way you get an array in your post array and can use it like so:
foreach ($_POST['interest'] as $interest) {
doStuff();
}
对于第三个问题,我假设您编写了一个JS方法, 将输入字段添加到表单?如果是这样,您可以实施 这样的限制:
For your third question I'm assuming you wrote a JS method that adds an input field to the form? If so you could implement a limit this way:
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++;
}
这篇关于jQuery追加输入字段并发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!