[javascript] How to prevent form from being submitted?

I have a form that has a submit button in it somewhere.

However, I would like to somehow 'catch' the submit event and prevent it from occurring.

Is there some way I can do this?

I can't modify the submit button, because it's part of a custom control.

This question is related to javascript html forms

The answer is


You can use inline event onsubmit like this

<form onsubmit="alert('stop submit'); return false;" >

Or

<script>
   function toSubmit(){
      alert('I will not submit');
      return false;
   }
</script>

<form onsubmit="return toSubmit();" >

Demo

Now, this may be not a good idea when making big projects. You may need to use Event Listeners.

Please read more about Inline Events vs Event Listeners (addEventListener and IE's attachEvent) here. For I can not explain it more than Chris Baker did.

Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.


The following works as of now (tested in chrome and firefox):

<form onsubmit="event.preventDefault(); return 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()


Try this one...

HTML Code

<form class="submit">
    <input type="text" name="text1"/>
    <input type="text" name="text2"/>
    <input type="submit" name="Submit" value="submit"/>
</form>

jQuery Code

$(function(){
    $('.submit').on('submit', function(event){
        event.preventDefault();
        alert("Form Submission stopped.");
    });
});

or

$(function(){
    $('.submit').on('submit', function(event){
       event.preventDefault();
       event.stopPropagation();
       alert("Form Submission prevented / stopped.");
    });
});

var form = document.getElementById("idOfForm");
form.onsubmit = function() {
  return false;
}

For prevent form from submittion you only need to do this.

<form onsubmit="event.preventDefault()">
    .....
</form>

By using above code this will prevent your form submittion.


Here my answer :

<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
    e.preventDefault();
    const name = e.target.name.value;
    renderSearching();

    return false;
}
</script>

I add event.preventDefault(); on onsubmit and it works.


You can add eventListner to the form, that preventDefault() and convert form data to JSON as below:

_x000D_
_x000D_
const formToJSON = elements => [].reduce.call(elements, (data, element) => {_x000D_
  data[element.name] = element.value;_x000D_
  return data;_x000D_
_x000D_
}, {});_x000D_
_x000D_
const handleFormSubmit = event => {_x000D_
    event.preventDefault();_x000D_
    const data = formToJSON(form.elements);_x000D_
    console.log(data);_x000D_
  //  const odata = JSON.stringify(data, null, "  ");_x000D_
  const jdata = JSON.stringify(data);_x000D_
    console.log(jdata);_x000D_
_x000D_
    (async () => {_x000D_
      const rawResponse = await fetch('/', {_x000D_
        method: 'POST',_x000D_
        headers: {_x000D_
          'Accept': 'application/json',_x000D_
          'Content-Type': 'application/json'_x000D_
        },_x000D_
        body: jdata_x000D_
      });_x000D_
      const content = await rawResponse.json();_x000D_
_x000D_
      console.log(content);_x000D_
    })();_x000D_
};_x000D_
_x000D_
const form = document.forms['myForm']; _x000D_
form.addEventListener('submit', handleFormSubmit);
_x000D_
<form id="myForm" action="/" method="post" accept-charset="utf-8">_x000D_
    <label>Checkbox:_x000D_
        <input type="checkbox" name="checkbox" value="on">_x000D_
    </label><br /><br />_x000D_
_x000D_
    <label>Number:_x000D_
        <input name="number" type="number" value="123" />_x000D_
    </label><br /><br />_x000D_
_x000D_
    <label>Password:_x000D_
        <input name="password" type="password" />_x000D_
    </label>_x000D_
    <br /><br />_x000D_
_x000D_
    <label for="radio">Type:_x000D_
        <label for="a">A_x000D_
            <input type="radio" name="radio" id="a" value="a" />_x000D_
        </label>_x000D_
        <label for="b">B_x000D_
            <input type="radio" name="radio" id="b" value="b" checked />_x000D_
        </label>_x000D_
        <label for="c">C_x000D_
            <input type="radio" name="radio" id="c" value="c" />_x000D_
        </label>_x000D_
    </label>_x000D_
    <br /><br />_x000D_
_x000D_
    <label>Textarea:_x000D_
        <textarea name="text_area" rows="10" cols="50">Write something here.</textarea>_x000D_
    </label>_x000D_
    <br /><br />_x000D_
_x000D_
    <label>Select:_x000D_
        <select name="select">_x000D_
            <option value="a">Value A</option>_x000D_
            <option value="b" selected>Value B</option>_x000D_
            <option value="c">Value C</option>_x000D_
        </select>_x000D_
    </label>_x000D_
    <br /><br />_x000D_
_x000D_
    <label>Submit:_x000D_
        <input type="submit" value="Login">_x000D_
    </label>_x000D_
    <br /><br />_x000D_
_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_


Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:

_x000D_
_x000D_
const element = document.querySelector('form');_x000D_
element.addEventListener('submit', event => {_x000D_
  event.preventDefault();_x000D_
  // actual logic, e.g. validate the form_x000D_
  console.log('Form submission cancelled.');_x000D_
});
_x000D_
<form>_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.

Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick .


To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:

<form onsubmit="return false;"></form>

Then wire up events using the onload or DOM ready if you're using a library.

_x000D_
_x000D_
$(function() {_x000D_
    var $form = $('#my-form');_x000D_
    $form.removeAttr('onsubmit');_x000D_
    $form.submit(function(ev) {_x000D_
        // quick validation example..._x000D_
        $form.children('input[type="text"]').each(function(){_x000D_
            if($(this).val().length == 0) {_x000D_
                alert('You are missing a field');_x000D_
                ev.preventDefault();_x000D_
            }_x000D_
        });_x000D_
    });_x000D_
});
_x000D_
label {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
#my-form > input[type="text"] {_x000D_
    background: cyan;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">_x000D_
    <label>Your first name</label>_x000D_
    <input type="text" name="first-name"/>_x000D_
    <label>Your last name</label>_x000D_
    <input type="text" name="last-name" /> <br />_x000D_
    <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.


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"