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

标签 javascript php jquery

$('#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/

相关文章:

javascript - 内部 (if) 2 个参数在 Firefox 上不起作用

php - Sentry 使用什么类型的加密

php - PHP While 循环中的 HTML 表单按钮

php - Laravel 检查缓存标签是否存在

javascript - 我如何在 UL 中显示 X 项并隐藏其余项?

javascript - Bootstrap 网格中断(不同高度的图像)

javascript - 使用 HTML5 工具提示会在 Google Chrome 上破坏页面

javascript - 如何将光标移动到 JavaScript 中文本区域的最后一个位置?

javascript - jQuery 事件仅影响元素的此实例

javascript - 在哪里放置小部件的脚本引用(部分页面)