83

I am trying to fire a function using Jquery when the form submit button is clicked, but the function needs to fire BEFORE the form is actually submitted.

I am trying to copy some div tag attributes into hidden text fields upon submission, and then submit the form.

I have managed to get this to work using the mouseover function (when the submit button is hovered over), but this will not work on mobile devices using touch.

$("#create-card-process.design #submit").on("mouseover", function () {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

I have played around with the submit function, but the values are not saved within the fields as the function fires when the form is submitted and not before.

Many thanks.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Matt Price
  • 1,371
  • 2
  • 9
  • 19
  • 4
    The `submit` event (on the form) should run when you click the submit button, and it will run before the form is submitted natively. You can also try using a `click` event on the submit button itself. – gen_Eric Feb 21 '14 at 15:46
  • What problems do you have with the `submit` function, I don't understand your last sentence. What does "values are not saved within the fields" mean? Do you have any other JavaScript (validation maybe) on the form? – gen_Eric Feb 21 '14 at 15:48
  • Can you give us a fiddle? If you want to ensure an animation is run before submit, using `timeout` is also an option. – Kevin Brown Feb 21 '14 at 15:48
  • You can get the values from the fields using `.val()` function. The values should be there. – kartikluke Feb 21 '14 at 15:52

8 Answers8

110

You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {
  // your code here
});
kartikluke
  • 2,375
  • 1
  • 19
  • 32
  • 1
    The question is how to add code before the submit. This answer explains how to prevent the submit, which are two different things. – Jan Sep 23 '22 at 15:02
91
$('#myform').submit(function() {
  // your code here
})

The above is NOT working in Firefox. The form will just simply submit without running your code first. Also, similar issues are mentioned elsewhere... such as this question. The workaround will be

$('#myform').submit(function(event) {

 event.preventDefault(); //this will prevent the default submit

  // your code here (But not asynchronous code such as Ajax because it does not wait for a response and move to the next line.)
  
 $(this).unbind('submit').submit(); // continue the submit unbind preventDefault
})
Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
Syed Waqas Bukhary
  • 5,130
  • 5
  • 47
  • 59
  • Is it still the case with Firefox? This answer was given 5 years ago. – Yevgeniy Afanasyev Mar 28 '21 at 23:01
  • 2
    I just installed Firefox to test it. I'm on version 87. The simple `submit` is doing it just fine, no need to `preventDefault`. I'm on jquery 3.5.1. – Yevgeniy Afanasyev Mar 28 '21 at 23:38
  • Is the code inside the submit callback function works? before the form submits? without using return false as mentioned in the accepted answer? – Syed Waqas Bukhary Mar 28 '21 at 23:47
  • The submit() is actually used to submit form, so if you wish to run your code before submit then you need to preventDefault When using only `return false` there is no way for you to continue submit form after your function runs ... but with combination of `preventDefault` and `unbind` you can continue with submit after running your function. https://api.jquery.com/submit/ – Syed Waqas Bukhary Mar 29 '21 at 00:05
  • Is the code inside the submit callback function works? - Yes. before the form submits? - Yes. If you return false the form won't get submitted? - Yes. – Yevgeniy Afanasyev Mar 29 '21 at 23:17
  • When using only `return false` there is no way for you to continue submit form... - yes it was the point. If you return false the form won't get submitted. – Yevgeniy Afanasyev Mar 29 '21 at 23:22
  • combination ... blah - blah - blah... If you want the form submitted then don't `return false`. It is very simple. – Yevgeniy Afanasyev Mar 29 '21 at 23:23
4

Based on Wakas Bukhary answer, you could make it async by puting the last line in the response scope.

$('#myform').submit(function(event) {

  event.preventDefault(); //this will prevent the default submit
  var _this = $(this); //store form so it can be accessed later

  $.ajax('GET', 'url').then(function(resp) {

    // your code here 

   _this.unbind('submit').submit(); // continue the submit unbind preventDefault
  })  
}
SoMa
  • 61
  • 3
4

I wanted to give a modern Oct, 2021 answer. Currently, $('form').on('submit', function(event) {...}) will never execute before the actual submission in a number of certain cases: FireFox and using HTML5 required on hidden inputs.

I have tested the following solution in Chrome, Firefox, and Brave. Simply set the onClick() of the submit button as your eventhandler. You can cancel the submission by event.preventDefault(); if you don't want the submit to happen. In addition, selecting a text or checkbox input, and hitting enter, still calls the onClick event, even though no-onClick happened, because the browser understands it as a shortcut for clicking your <input type="submit">.

var allowSubmit = false;
document.querySelector('#submit').addEventListener('click', function(event) {
    if(allowSubmit) {
        console.log("Submit allowed.");
        return true;
    }
    
    console.log("Submit prevented.");
    
    event.preventDefault();
    return false;
});
<input type="submit" id="submit" value="Submit Button">
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
3

You can do something like the following these days by referencing the "beforeSubmit" jquery form event. I'm disabling and enabling the submit button to avoid duplicate requests, submitting via ajax, returning a message that's a json array and displaying the information in a pNotify:

jQuery('body').on('beforeSubmit', "#formID", function() {
    $('.submitter').prop('disabled', true);
    var form = $('#formID');
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        data   : form.serialize(),
        success: function (response)
        {
            response = jQuery.parseJSON(response);
            new PNotify({
                text: response.message,
                type: response.status,
                styling: 'bootstrap3',
                delay: 2000,
            });
            $('.submitter').prop('disabled', false);
        },
        error  : function ()
        {
            console.log('internal server error');
        }
    });
});
Fi Horan
  • 503
  • 4
  • 14
2

Aghhh... i was missing some code when i first tried the .submit function.....

This works:

$('#create-card-process.design').submit(function() {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

Thanks for all the comments.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Matt Price
  • 1,371
  • 2
  • 9
  • 19
1

You can use some div or span instead of button and then on click call some function which submits form at he end.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>
Skriptotajs
  • 844
  • 6
  • 15
0

Just because I made this mistake every time when using the submit function.

This is the full code you need:

Add the id "yourid" to the HTML form tag.

<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>

the jQuery code:

$('#yourid').submit(function() {
  // do something
});
meck373
  • 1,114
  • 1
  • 18
  • 31