使用preventDefault()时,如何在单击按钮时提交表单? [英] How can I submit form on button click when using preventDefault()?

查看:84
本文介绍了使用preventDefault()时,如何在单击按钮时提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的.preventDefault()来防止用户单击[ENTER]键时提交表单.问题在于,当我单击提交"按钮时,它也停止了表单的提交.

I'm using jQuery's .preventDefault() to prevent form submit when users clicks the [ENTER] key. The problem is that it also stops the form submitting when I click the submit button.

我看到关于.preventDefault()的Stackoverflow上有很多线程,但是没有一个能解决我的问题.

I see there are many threads on Stackoverflow in regards of .preventDefault(), but none of them addresses my problem.

这是我目前正在使用的代码.

Here's the code I'm currently working on.

// Part of my form
<form id="subscription_order_form" class=""  method="post" action="some_url"> 
  <button id="btn_order" type="submit">Order</button>
</form>

// Prevent the form to be submitted on ENTER
$('#subscription_order_form').submit(function(e){
  e.preventDefault();
});

// Controll data
$('#btn_order').click(function(){
  checkMandatoryFields();
});


// Check mandatory fields before subitting:
function checkMandatoryFields(e){

  // Code for testing here

  // Set "error" message and abort submission
  if(msg.length > 0) {
    // Do something
  } else {

    //submit or trigger is not recognized as functions
    $('#subscription_order_form').submit(); //.trigger('submit');

  }
}

任何人都可以告诉我他在单击按钮时提交表单的代码是什么吗?

Can anyone please tell my what he code for submitting the form on button click is?

推荐答案

在DOM节点上触发提交事件,而不是jQuery对象.

Trigger the submit event on the DOM Node, not a jQuery Object.

$('#subscription_order_form')[0].submit();

$('#subscription_order_form').get(0).submit();

document.getElementById("subscription_order_form").submit();

这绕过了jQuery绑定事件,允许表单正常提交.

This bypasses the jQuery bound event allowing the form to submit normally.

这篇关于使用preventDefault()时,如何在单击按钮时提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆