284

One way to stop form submission is to return false from your JavaScript function.

When the submit button is clicked, a validation function is called. I have a case in form validation. If that condition is met I call a function named returnToPreviousPage();

function returnToPreviousPage() {
    window.history.back();
}

I am using JavaScript and Dojo Toolkit.

Rather going back to the previous page, it submits the form. How can I abort this submission and return to the previous page?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Muhammad Imran Tariq
  • 22,654
  • 47
  • 125
  • 190

15 Answers15

394

You can use the return value of the function to prevent the form submission

<form name="myForm" onsubmit="return validateMyForm();"> 

and function like

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValue field to false to get it to work.

Thanks Sam for sharing information.

EDIT :

Thanks to Vikram for his workaround for if validateMyForm() returns false:

 <form onsubmit="event.preventDefault(); validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
  • 2
    Just a guess: it doesn't work for me in the latest version of Chrome. – Sam Jul 07 '13 at 01:39
  • 7
    Anything that returns `false` doesn't seem to have any effect; Chrome still submits the form. For example, `onsubmit="return false;"`. However, setting the event handler's parameter's `returnValue` field to `false` does work for me. – Sam Jul 08 '13 at 04:21
  • Thanks for providing information. which version of chrome you are using? – Hemant Metalia Jul 08 '13 at 04:40
  • 4
    Hi Sam / Hemant, can you provide code sample as for how to set event handler's parameter's returnValue field to false please. – JackDev Sep 02 '13 at 02:03
  • @JackDev you can simply write return false; – Hemant Metalia Sep 02 '13 at 08:49
  • 2
    I think since this is the accepted answer, it should probably tell how to do this properly. I along with JackDev, are wondering how to get this to work properly. As is, this does *not* work – Cruncher Nov 18 '13 at 20:35
  • @JackDev,@Cruncher,@Mariano please go through http://www.htmlgoodies.com/beyond/javascript/advanced-javascript-event-handling.html – Hemant Metalia Nov 19 '13 at 04:42
  • 2
    If `validateMyForm()` has errors `return false` will not be reached. So this may fail. After many hours, I found a solution that works and posted it below. – Vikram Pudi May 14 '14 at 05:25
  • @VikramPudi thanks for work around. I am editing my answer with your solution as well. – Hemant Metalia Jan 21 '16 at 04:50
  • 1
    This answer is wrong and confusing for reasons too many to enumerate. See @GregGuida's answer for `preventDefault()`, also: [`returnValue` is not even a standard](http://stackoverflow.com/questions/20045162/event-returnvalue-is-deprecated-please-use-the-standard-event-preventdefault). – Crescent Fresh May 26 '16 at 19:41
  • You cannot use `onsubmit` attribute with `Content-Security-Protection` unless you add `unsafe-inline` which is definitely not recommended. Use real event handlers suggested by other answers, instead. – Mikko Rantalainen Apr 11 '17 at 06:21
  • 1
    @Sam `Event.returnValue` has been deprecated. Please see: https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue – Ralph David Abernathy Jul 16 '21 at 16:30
154

Use prevent default

Dojo Toolkit

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

jQuery

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

Vanilla JavaScript

if (element.addEventListener) {
    element.addEventListener("submit", function(evt) {
        evt.preventDefault();
        window.history.back();
    }, true);
}
else {
    element.attachEvent('onsubmit', function(evt){
        evt.preventDefault();
        window.history.back();
    });
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Greg Guida
  • 7,302
  • 4
  • 30
  • 40
60

The following works as of now (tested in Chrome and Firefox):

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vikram Pudi
  • 1,157
  • 10
  • 6
33

Base on @Vikram Pudi answer, we can also do like this with pure Javascript

<form onsubmit="submitForm(event)">
    <input type="text">
    <input type="submit">
</form>

<script type="text/javascript">

    function submitForm(event){
        event.preventDefault();


    }
</script>
Linh
  • 57,942
  • 23
  • 262
  • 279
20

Just use a simple button instead of a submit button. And call a JavaScript function to handle form submit:

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

Function within a script tag:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

You can also try window.history.forward(-1);

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • I like this approach because it allows for my use case, callbacks. – Eddie Feb 21 '13 at 01:47
  • 21
    This prevents the use of the enter key to submit the form. Also, new HTML5 attributes such as `required` won't work. – Sam Jul 07 '13 at 01:40
12

Lots of hard ways to do an easy thing:

<form name="foo" onsubmit="return false">
Danial
  • 1,496
  • 14
  • 15
  • 6
    This exact answer (OK, not exact, since yours is missing a semi-colon) was submitted 8 months earlier, and has negative votes for good reason. This works _most_ of the time. But not on all browsers **all** of the time. – Auspex Sep 28 '17 at 08:25
  • 6
    I didn't say you _needed_ a semicolon; I pointed out that that was all that was different between your answer and a __much__ older one. The fact that you are now asking me to point out which browsers don't support it (I never said there were any, I merely pointed out that it won't always work), proves that you _still_ haven't read this whole page. – Auspex Oct 03 '17 at 18:38
  • 3
    I don't usually examine the down-votes, except I didn't know that people were down-voting correct code. Technically, the semicolon is extraneous, so it's wrong. And you said "yours is missing the semicolon" implying that it's needed, which is wrong. You say it "won't always work" but you can't point out a single case or browser where it won't work? This is sound logic? It's correct code. So unless you can point out the case where it won't work, then you don't have a point at all. – Danial Oct 03 '17 at 19:56
  • How does this not have more upvotes? It's far more terse compared to the other examples. – Sal Alturaigi Jun 01 '20 at 17:02
  • Probably because the title doesn't match what the guy was actually asking. – Danial Jun 03 '20 at 04:28
  • This solution works for me all of the time (Google Chrome). – Jerry Sep 21 '22 at 20:48
9

All your answers gave something to work with.

FINALLY, this worked for me: (if you dont choose at least one checkbox item, it warns and stays in the same page)

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form name="helloForm" action="HelloWorld" method="GET"  onsubmit="valthisform();">
            <br>
            <br><b> MY LIKES </b>
            <br>
            First Name: <input type="text" name="first_name" required>
            <br />
            Last Name: <input type="text" name="last_name"  required />
            <br>
            <input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
            <input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
            <input type="radio" name="modifyValues" value="asis"      required="required" checked="checked">Do not convert <br>
            <br>
            <input type="checkbox" name="c1" value="maths"     /> Maths
            <input type="checkbox" name="c1" value="physics"   /> Physics
            <input type="checkbox" name="c1" value="chemistry" /> Chemistry
            <br>

            <button onclick="submit">Submit</button>

            <!-- input type="submit" value="submit" / -->
            <script>
                <!---
                function valthisform() {
                    var checkboxs=document.getElementsByName("c1");
                    var okay=false;
                    for(var i=0,l=checkboxs.length;i<l;i++) {
                        if(checkboxs[i].checked) {
                            okay=true;
                            break;
                        }
                    }
                    if (!okay) { 
                        alert("Please check a checkbox");
                        event.preventDefault();
                    } else {
                    }
                }
                -->
            </script>
        </form>
    </body>
</html>
Doug
  • 3,312
  • 1
  • 24
  • 31
Gdba
  • 91
  • 1
  • 1
6

I would recommend not using onsubmit and instead attaching an event in the script.

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

Then use preventDefault() (or returnValue = false for older browsers).

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}
Isaac Abramowitz
  • 542
  • 5
  • 17
2

Lets say you have a form similar to this

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

Here is the javascript for the confirmAction function

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.

If that is not the case let me know

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
  • 1
    The combination of `preventDefault()` and `returnToPreviousPage()` is perfect and elegant. It interrupts normal operation just like you'd design any exception catcher to work. +1. – user1934286 Apr 09 '20 at 21:03
2

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

2

Simply do it....

<form>
<!-- Your Input Elements -->
</form>

and here goes your JQuery

$(document).on('submit', 'form', function(e){
    e.preventDefault();
    //your code goes here
    //100% works
    return;
});
Dev Matee
  • 5,525
  • 2
  • 27
  • 33
1

Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:

    if(check if your conditions are not satisfying) 
    { 
    event.preventDefault();
    alert("validation failed false");
    returnToPreviousPage();
    return false;
    }
    alert("validations passed");
    return true;
    }

Thanks to Hemant and Vikram for putting me on the right track.

Jesperai
  • 31
  • 2
1

Disabling submit button also can help to prevent form submission.

<input style="display:none" type="submit" disabled>

1

Even though it seems obvious it should be noted that you will also have to then submit your form if the validation is good to go if you block submitting with prevent default. I provided a complete example below of validating doc type and then submitting if its the right doc type.

<h2>Document Upload</h2>
<script>
var CanContinue = false;

function validateMyForm()
{
if(CanContinue == false)
  { 
    alert("You must upload a PDF, PNG, or JPG of your document.");


return false;

  }
  document.getElementById("myForm").submit();

  return true;
}

function getFileNameWithExt(event) {

  if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
return;
  }

  const name = event.target.files[0].name;
  const lastDot = name.lastIndexOf('.');

  const fileName = name.substring(0, lastDot);
  const ext = (name.substring(lastDot + 1)).toUpperCase();
    if (ext =="JPG") {
    extension.value = "image/jpeg";
    CanContinue = true;

} else if (ext =="JPEG") {
  extension.value = "image/jpeg";
  CanContinue = true;

} else if (ext =="PNG") {
  extension.value = "image/png";
  CanContinue = true;

} else if (ext =="PDF") {
  extension.value = "application/pdf";
  CanContinue = true;

} else {
  alert("You must upload a PDF, PNG, or JPG of your document.");
  CanContinue = false;
}

  outputfile.value = fileName;


}

</script>


                <form method="post" id="myForm" action="/wheregoing" enctype="multipart/form-data" onsubmit="event.preventDefault(); validateMyForm();">
                
                Please upload a JPG, PNG, or PDF of the front of the document.
                <input id='inputfile' type="file" name="dafile" onChange='getFileNameWithExt(event)' required>
               
             <input id='extension' type='hidden' name='ContentType' value="">
                <input type="submit">
                </form>
0

Most simple and short code

<form onsubmit="return false">

For better cross-browser compatibility and maintainability, you can use JavaScript to attach an event listener to the form element and prevent the default form submission behavior

<form id="myForm">
  <!-- Form fields and elements -->
  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById('myForm').addEventListener('submit', function(event) {
    event.preventDefault();
    // Additional logic or actions
  });
</script>
tec
  • 5
  • 6