Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I submit form on button click when using preventDefault()?

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.

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?

like image 824
Steven Avatar asked Jul 20 '12 14:07

Steven


2 Answers

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

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

or

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

or

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

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

like image 67
Kevin B Avatar answered Oct 05 '22 04:10

Kevin B


Change the submit button to a normal button and handle submitting in its onClick event.

As far as I know, there is no way to tell if the form was submitted by Enter Key or the submit button.

like image 35
Hans Hohenfeld Avatar answered Oct 05 '22 04:10

Hans Hohenfeld