Coder Perfect

What should I do before submitting?


I’ve created a form with a button that submits it. Before I submit anything, I need to do anything. I tried using onClick on that button, but it only worked after I submitted the form.

I can’t disclose the code, but what should I do in jQuery or JS to deal with this in general?

Asked by Jimmy

Solution #1

If you have a form, fill it out as follows:

<form id="myform">

To do something before the form is submitted, use the jQuery code below:

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

Answered by Dan Breen

Solution #2

Assuming you have a document that looks like this:

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


With jQuery, you can add an onsubmit-event like this:

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

If you return false, the form will not be submitted after the function; however, if you return true or nothing, the form will be submitted normally.

For more information, see the jQuery documentation.

Answered by acme

Solution #3

Before submitting the form, you can use onclick to perform some JavaScript or jQuery code like this:

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

Answered by James Johnson

Solution #4

Make the submit button a button rather than a “submit” button. Then, using the onclick event, execute some javascript. Before you actually upload your data, you can do whatever you want there.

Answered by rogerlsmith

Post is based on