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.
You need to use
$(this).parents('form').submit()
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
FIDDLE
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
Ok, first e.preventDefault();
it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this
$('#subscription_order_form').submit(function(e){
$.ajax({
url: $(this).attr('action'),
data : $(this).serialize(),
success : function (data){
}
});
e.preventDefault();
});