How to Prevent Form from Being Submitted

How to prevent form from being submitted?

Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...

html

<form onsubmit="return mySubmitFunction(event)">
...
</form>

script

function mySubmitFunction()
{
someBug()
return false;
}

returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

function mySubmitFunction(e) {
e.preventDefault();
someBug();
return false;
}

In this case, even with the bug the form won't submit!

Alternatively, a try...catch block could be used.

function mySubmit(e) { 
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}

Prevent form submission in the onsubmit event

The content is not changing back. Actually, the form is being submitted and the page is essentially being refreshed.

You need to call .preventDefault(); on the submit event to prevent the form submission like this:

function myFunction(evt) { 
evt.preventDefault();

// ... other code
};

Or better yet, ditch the form altogether, change the type="submit" to type="button", then attach an event handler to the button like this:

<body>
<h1>My First JavaScript V2</h1>
<p id="demo"></p>
<input type="text" size="5" name="a" id="number1"> +
<input type="text" size="5" name="b" id="number2"> =
<span id="result">?</span>
<br>
<input type="button" class="calculate" value="calculate server side">
<p id="feedback">feedback</p>
</body>


$(function() {
$('.calculate').click(function() {
alert("done");
var a = parseInt(document.getElementById('number1').value);
var b = parseInt(document.getElementById('number2').value);
var c = a + b;
$.get('/_add_numbers', {
number: c
}, function(data, status) {
res = JSON.parse(data);
alert(status);
$("#feedback").text("change");
alert("show");
});
});
});

Stop form submission when using JavaScript

You don't have to return false to stop the form from being submitted. You need to use the event's preventDefault() method, and submit the form using JS if the data is valid. Like this:

function validateform(e) { // take the event as parameter
e.preventDefault(); // stop the submission

var cnic1 = document.getElementById("cnic1");

if (cnic1.value.length < 15) {
window.alert("Invalid CNIC");
cnic1.focus();
} else {
form.submit();
}
}

var form = document.getElementsByName('applyform')[0];
form.addEventListener('submit', validateform);

I also added the listener using JS just so you can be sure the event parameter is passed to your validation function. Remove the onsubmit="..." from your form.

JavaScript code to stop form submission

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

Prevent users from submitting a form by hitting Enter

You can use a method such as

$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});

In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:

function validationFunction() {
$('input').each(function() {
...

}
if(good) {
return true;
}
return false;
}

$(document).ready(function() {
$(window).keydown(function(event){
if( (event.keyCode == 13) && (validationFunction() == false) ) {
event.preventDefault();
return false;
}
});
});

React - Preventing Form Submission

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button>submits form too</button>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

Example: http://jsbin.com/vowuley/edit?html,js,console,output

Prevent form submission using Flask

Fixed by moving the onsubmit to form rather than on the submit button.

<form name="ip_checks" method=post enctype=multipart/form-data onsubmit="return ValidateIPaddress(document.ip_checks.IPs)">
<p><label for="ipaddresses" class="form-label">IP Addresses:</label>
<textarea name="IPs" cols="40" rows="2" class="form-control"></textarea></p>
<p><input type="submit" value="Submit" name="Submit" class="btn btn-primary" /></p>
</form>

Prevent form from submitting if form is empty

Why not just use the required attribute? No JS necessary

<input id="email" type="email" required>

This will check if the email field is not empty and additionally entered string is a valid email format.

Note that HTML "required" does not work in safari browser whose version less than Safari 10.1 (May 2017)

Edit:
To display a custom message, subscribe to the invalid event

const email = document.getElementById('email');
email.addEventListener('invalid', function(e){
if (email.value == '')
email.setCustomValidity('Where is the email?');
else if (email.validity.typeMismatch)
email.setCustomValidity('Email address be invalid!');
});

You can learn more about Form Validation at Mozilla

How to prevent form submission until onsubmit function completes?

Use an id and event listener, prevent default on submit, wrap your function in a promise, and only submit if the result is true:

function getLocation(e) {  // Create new promise  return new Promise(resolve => {    if (navigator.geolocation) {      // Since getCurrentPosition is asynchronous, resolve in the onsuccess callback.      navigator.geolocation.getCurrentPosition(        position => {          onGeoSuccess(position);          // Resolving here will return back to the .then()          resolve();        },        error => {          onGeoError(error);          resolve();        }      );    } else {      alert("Geolocation is not supported by this browser.");      // Return to the .then()      resolve();    }  });}
function onGeoSuccess(position) { document.getElementById("currentUserLattitude").value = position.coords.latitude; document.getElementById("currentUserLongitude").value = position.coords.longitude;}
function onGeoError(err) { alert("Error code " + err.code + ". " + err.message);}
document.getElementById("form").addEventListener("submit", e => { // Prevent submission e.preventDefault(); // Call your function and wait for a response getLocation().then(() => { // Submit the form return e.target.submit(); });});
<form id="form" action="/login" onsubmit="getLocation()" method="POST">
<button type="submit" class="btn btn-dark">Login</button> <input id="currentUserLattitude" type=hidden name="currentLocation" value="placeholder"> <input id="currentUserLongitude" type=hidden name="currentLocation" value="placeholder">
</form>

How to prevent form submit when a button clicked?

I don't agree with the javascript answers. They work, but they're not fixing the cause of the problem.

The form is being submitted because the <button> element has a type of submit by default (see the spec here).

You can get around this by putting type="button" in the html like so:

 <button type="button" class="btn btn-default" id="btn-area">


Related Topics



Leave a reply



Submit