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.
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;
}
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();" >
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.
<form onsubmit="return false;" >
does not work for me.
Attach an event listener to the form using .addEventListener()
and then call the .preventDefault()
method on event
:
const element = document.querySelector('form'); element.addEventListener('submit', event => { event.preventDefault(); // actual logic, e.g. validate the form console.log('Form submission cancelled.'); });
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 .
$("button").click(function(e) { e.preventDefault() });
querySelector
because it returns the first element in the document matching the given selector. This can make your code break if a second form is later added earlier in the page, something that happens frequently, such as if you decide to later add a login form to the header, or even if an invisible or hidden form is added by a CMS module. (I've seen this happen on projects.) Using getElementById
is more reliable because the ID must be unique, at least per DOM tree, according to HTML specifications, and validators will catch when it is not.
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.");
});
});
stopPropagation
was the only thing that worked in my case. thanks! :)
var form = document.getElementById("idOfForm");
form.onsubmit = function() {
return false;
}
.onsubmit
is a bad idea because it prevents you from attaching multiple submit
callbacks to one element. I recommend using .addEventListener()
.
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.
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; }
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.
You can add eventListner to the form, that preventDefault()
and convert form data to JSON as below:
const formToJSON = elements => [].reduce.call(elements, (data, element) => { data[element.name] = element.value; return data; }, {}); const handleFormSubmit = event => { event.preventDefault(); const data = formToJSON(form.elements); console.log(data); // const odata = JSON.stringify(data, null, " "); const jdata = JSON.stringify(data); console.log(jdata); (async () => { const rawResponse = await fetch('/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: jdata }); const content = await rawResponse.json(); console.log(content); })(); }; const form = document.forms['myForm']; form.addEventListener('submit', handleFormSubmit);
<form v-on:submit.prevent="yourMethodHere">
The submit event will no longer reload the page. It runs your method.
From vue documentation: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers
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.
Success story sharing
false
directly fromonsumbit
?(<form onsubmit="return mySubmitFunction(evt)">)
.Otherwise it gives Undefined error.event
as parameter in Chrome, just if anyone's struggling with this..