[jquery] Jquery function BEFORE form submission

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.

This question is related to jquery forms form-submit

The answer is


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
});

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
  })  
}

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.


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>

$('#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
})

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');
        }
    });
});

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to form-submit

Setting onSubmit in React.js Jquery function BEFORE form submission How to locate and insert a value in a text box (input) using Python Selenium? Submit form without reloading page How to check if text fields are empty on form submit using jQuery? Submitting HTML form using Jquery AJAX Serializing and submitting a form with jQuery and PHP How do I use an image as a submit button? How to pass value from <option><select> to form action validation of input text field in html using javascript