gpt4 book ai didi

javascript - jquery追加输入字段并发布

转载 作者:行者123 更新时间:2023-11-28 20:00:33 27 4
gpt4 key购买 nike

$('#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 post 的表单。有一个按钮可以附加更多输入类型文本。

我的问题

1 当用户单击并附加更多输入字段时,在 $.post(... 一侧,如何添加更多脚本,以便我可以将其发布到下一页?

2 在我的 php 页面

if(isset($_POST['interest1'], $_POST['interest2']...)){}

我如何知道用户添加了多少个额外的输入字段?

3 如何限制用户最多可以附加 3 个输入字段?

最佳答案

您是否在发布请求中手动设置表单字段?坏主意,你最好使用 jQuery 的序列化方法:

$.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++;
}

关于javascript - jquery追加输入字段并发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723969/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com