首页 > 解决方案 > 在提交表单之前,如何使用 jquery 将表单字段添加到表单中

问题描述

在我的页面上,我有两个按钮。

  1. 无需注册即可购买
  2. 进行购买并将我添加到邮件列表中。

两个按钮都提交相同的表单,但是我需要其中一个按钮在表单提交之前将隐藏的表单字段添加到表单中,以允许在生成的 PHP 中使用 POST 变量。

我无法让以下工作。TIA

    jQuery(document).ready(function(){

    jQuery('.place-order-with-newsletter').on('click', function(){

        jQuery('form#dc-checkout-form').submit(function(){

            jQuery('<input />').attr('type', 'hidden')
            .attr('name', 'dc-opt-in')
            .attr('value', '1')
            .appendTo('form#dc-checkout-form')
            return true;
        })

    })

})

标签: jquery

解决方案


将按钮移到表单外或将类型更改为“按钮”

<button type="button"></button>

默认情况下,表单上的按钮使提交。

并将所有代码移动到单击事件并最终提交表单

jQuery(document).ready(function(){
    jQuery('.place-order-with-newsletter').on('click', function(){
        jQuery('<input />').attr('type', 'hidden')
        .attr('name', 'dc-opt-in')
        .attr('value', '1')
        .appendTo('form#dc-checkout-form')
        jQuery('form#dc-checkout-form').submit()
    })
})

推荐阅读