Form auto-submission tips for jQuery

jQuery form auto submission with submit() method.

jQuery provides method called submit() available to <form> Object.

$('form').submit();

It also passes callback function that executes before form submit event fires.

$('form').submit(function(){
     // do form validation here
});

You could use callback within above function to validate form.

$('form').submit(function () {
    if ($('#email').val() == "") {
        alert("Please enter Email");
        return false;
    }
    return true;
});

Now whenever you call this function from element’s onclick event it form will be submitted.

$('button').click(function(){
     $('form').submit();
});

Other way to get this done is jQuery on() method.

$('form').on('submit',function () {
    if ($('#email').val() == "") {
        alert("Please enter Email");
        return false;
    }
    return true;
});

  Things to keep in mind.

  • Don’t use “submit” attribute as name or id of any elements. (i.e <input type=”submit” name=”submit”> it may create issue firing auto-submit event as well as form validation.
  • Don’t break <form> tags or create child <form> tags within <form>

jQuery trigger method to make form autosubmit

jQuery provides trigger(‘EVENT_NAME’) method provide to auto fire elements programmatically. All you need to do it. just call it by supplying ‘submit’ as argument.

$('button').click(function(){
     $('form').trigger('submit');
});

or more way is you simulate submit button’s click event, so whatever events are attached with click event (i.e. validation and other stuffs will be called)

$('form').find('input[type="submit"]').trigger('click');

 

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

JavaScript AJAX variables truncation issue FIX

Next Post

AJAX style multiple images upload using HTML5, JSON and jQuery

Related Posts