How to prevent form from being submitted?
Clash Royale CLAN TAG#URR8PPP
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.
@Rafael: True... but that would be a last resort - this is a very complex control.
– Nathan Osman
Jul 28 '10 at 6:00
@Raf that's asp.net based, and also not a best practice. But its essentially correct. I'd just avoid peeking at the source and using the control name, as it may change if someone edits the page. Unintended side effects and such.
– Will
Jul 28 '10 at 11:40
7 Answers
7
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...
false
html
<form onsubmit="return mySubmitFunction(evt)">
...
</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.
false
preventDefault
function mySubmitFunction(evt)
evt.preventDefault();
someBug();
return false;
In this case, even with the bug the form won't submit!
Alternatively, a try...catch
block could be used.
try...catch
function mySubmit(evt)
evt.preventDefault();
try
someBug();
catch (e)
throw new Error(e.message);
return false;
Why not return
false
directly from onsumbit
?– ProfK
Mar 22 '13 at 9:02
false
onsumbit
You might want to show an error message to the user in the onsubmit. Fore example, "complete this mandatory field then submit". In that case event.preventDefault will come in very handy
– Mark Chorley
May 3 '13 at 9:26
@ProfK if you use event.preventDefault() it won't matter regardless, try/catch would just be part of your error handling
– Ben Rowe
Aug 29 '13 at 21:35
<form onsubmit="return mySubmitFunction(event)"> worked ... had to use the word event in brackets in firefox
– danday74
Sep 17 '16 at 23:37
@BenRowe You Should add evt parameter to the called method.
(<form onsubmit="return mySubmitFunction(evt)">)
.Otherwise it gives Undefined error.– UfukSURMEN
Jan 27 '17 at 10:21
(<form onsubmit="return mySubmitFunction(evt)">)
You can use inline event onSubmit
like this
onSubmit
<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.
Attach an event listener to the form using .addEventListener()
and then call the .preventDefault()
method on event
:
.addEventListener()
.preventDefault()
event
const element = document.querySelector('form');
element.addEventListener('submit', event =>
event.preventDefault();
// actual logic, e.g. validate the form
console.log('Form submission cancelled.');
);
<form>
<button type="submit">Submit</button>
</form>
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.
submit
onsubmit
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
.
.onsubmit
form
& for jquery:
$("button").click(function(e) e.preventDefault() );
– Nixen85
Mar 20 at 15:23
$("button").click(function(e) e.preventDefault() );
This was the only answer that worked for me.
– Rohmer
Jul 17 at 4:26
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.");
);
);
There is no jQuery tag in this question.
– Michał Perłakowski
Dec 18 '15 at 2:33
@Gothdo and yet the solution is still the same. crazy right?
– Kevin B
Jan 26 '16 at 23:27
@KevinB ...no? -
– Michał Perłakowski
Jan 26 '16 at 23:43
@Gothdo yea, it's exactly the same. eventObject.preventDefault. The way you bind the handler doesn't change the solution. I would even argue your answer is no different than the accepted one.
– Kevin B
Jan 26 '16 at 23:44
Except, jQuery...
– Geoffrey Hale
Nov 1 '16 at 18:04
var form = document.getElementById("idOfForm");
form.onsubmit = function()
return false;
I think that using
.onsubmit
is a bad idea because it prevents you from attaching multiple submit
callbacks to one element. I recommend using .addEventListener()
.– Michał Perłakowski
Dec 18 '15 at 2:33
.onsubmit
submit
.addEventListener()
Even if you have set an event handler via the property .onsubmit, you can still add additional handlers via .addEventListener(). The handler registered by the property will be invoked first then the ones registered with .addEventListener() in the order in which they were registered.
– Daniel Granger
Jan 2 '16 at 21:37
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()
false
event
e.preventDefault()
onsubmit="return validateMyForm();" is enough but validateMyForm() should return true or false.
– Adrian P.
Sep 30 '16 at 18:55
works for me. Thanks.
– arsho
May 1 '17 at 7:46
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.
$(function()
var $form = $('#my-form');
$form.removeAttr('onsubmit');
$form.submit(function(ev)
// quick validation example...
$form.children('input[type="text"]').each(function()
if($(this).val().length == 0)
alert('You are missing a field');
ev.preventDefault();
);
);
);
label
display: block;
#my-form > input[type="text"]
background: cyan;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">
<label>Your first name</label>
<input type="text" name="first-name"/>
<label>Your last name</label>
<input type="text" name="last-name" /> <br />
<input type="submit" />
</form>
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.
action
window.location
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
You could still access the submit button. Render the page and grab its ClientID by viewing the page source. Then, using something like jQuery you could do something like $('#ctl01_cph01_controlBtn1').click(function() return false;);
– rebelliard
Jul 28 '10 at 5:59