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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With