How to do something before on submit?

JavascriptJqueryHtml

Javascript Problem Overview


i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit.

I can't share the code but, generally, what should I do in jQuery or JS to handle this?

Javascript Solutions


Solution 1 - Javascript

If you have a form as such:

<form id="myform">
...
</form>

You can use the following jQuery code to do something before the form is submitted:

$('#myform').submit(function() {
    // DO STUFF...
    return true; // return false to cancel form action
});

Solution 2 - Javascript

Assuming you have a form like this:

<form id="myForm" action="foo.php" method="post">
   <input type="text" value="" />
   <input type="submit" value="submit form" />

</form>

You can attach a onsubmit-event with jQuery like this:

$('#myForm').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

If you return false the form won't be submitted after the function, if you return true or nothing it will submit as usual.

See the jQuery documentation for more info.

Solution 3 - Javascript

You can use onclick to run some JavaScript or jQuery code before submitting the form like this:

<script type="text/javascript">
    beforeSubmit = function(){
        if (1 == 1){
            //your before submit logic
        }        
        $("#formid").submit();            
    }
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />

Solution 4 - Javascript

make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.

Solution 5 - Javascript

Form:

<form id="formId" action="/" method="POST" onsubmit="prepareForm()">
   <input type="text" value="" />
   <input type="submit" value="Submit" />
</form>

Javascript file:

function prepareForm(event) {
  event.preventDefault();
  // Do something you need
  document.getElementById("formId").requestSubmit();
}

Note: If you're supporting Safari (which you probably are) you'll need to pull in a polyfill for requestSubmit()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJimmyView Question on Stackoverflow
Solution 1 - JavascriptDan BreenView Answer on Stackoverflow
Solution 2 - JavascriptacmeView Answer on Stackoverflow
Solution 3 - JavascriptJames JohnsonView Answer on Stackoverflow
Solution 4 - JavascriptrogerlsmithView Answer on Stackoverflow
Solution 5 - JavascriptStefanyuk YuriyView Answer on Stackoverflow