[javascript] JavaScript code to stop form submission

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?

This question is related to javascript html forms

The answer is


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

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>

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().


Lots of hard ways to do an easy thing:

<form name="foo" onsubmit="return false">

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


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

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.


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


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.


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

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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

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"