How to disable html form from navigating on submit? - javascript

Lets say I have this form
<form onsubmit="submitData();">
<input type="text" pattern="^[A-z]+$" required>
<button type="submit">OK</button>
</form>
Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern).
If I switch the value of onsubmit on the form to "return false;" then it won't navigate but "submitData(); return false;" doesn't work. Any other ideas?

Try adding e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) {, like this:
function submitData(e) {
e.preventDefault();
...
}
See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Just add event.preventDefault that is automatically pass by the form to the function:
function submitData(event){
event.preventDefault();
//your code will be here
}
read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Use event.preventDefault().
Learn more: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

add this to your code:
document.getElementById("addYourTagHERE").addEventListener("onsubmit", function(event){
event.preventDefault()
});
or this in your function:
function submitData(event) {
event.preventDefault();
}

You'd want to cancel the default action of the submit event handler, so:
function submitData() {
// whatever logic you have...
return false;
}
I believe this works too:
function submitData( e ) {
e.preventDefault();
// whatever logic you have...
}

Related

JS - When my Function removes a child Element all child Elements disappear [duplicate]

I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.
It's quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?
Buttons like <button>Click to do something</button> are submit buttons.
Set type="button" to change that. type="submit" is the default (as specified by the HTML spec):
The missing value default and invalid value default are the Submit Button state.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button" your form will not be submitted.
<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.
function forms_ini(){
for(var form of document.getElementsByTagName('form')){
form.addEventListener('submit', function(ev){
ev.preventDefault()
})
}
}
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}

Why is this JavasScript validation not working in Firefox

I have a form with text input and button.
There is a bit of JavaScript to validate whether the username is null or not. If it is null it will show a validation message, otherwise will submit the form.
Problem is the onclick even does not fire in Firefox. It works in every other browser.
Can someone please point out where I am going wrong? Thanks a lot.
HTML:
<form name="myForm" action="TestController">
<input type="text" width="50" name="username" />
<button onclick="submitForm()">Go</button>
<span class="errSpan"></span>
</form>
JavaScript:
(function(NAMESPACE){
NAMESPACE.submitForm = function(){
console.log('invoked');
window.event.preventDefault();
console.log(window.myForm.username.value);
if(window.myForm.username.value === "")
document.getElementsByClassName('errSpan')[0].innerHTML = 'cannot be null';
else {
document.myForm.submit();
}
}
})(window);
Here is link to JsFiddle
In firefox window.event is undefined, and your code fail with error.
Use addEventListener to add submit event for form, and remove the onclick statement from button.
window.myForm.addEventListener('submit', function (e) {
e.preventDefault();
//any code what you want
});
First you should pass the event to the submitForm() method.
onclick="submitForm(event)"
then use that event argument to call preventDefault
NAMESPACE.submitForm = function(e){
console.log('invoked');
e.preventDefault();
console.log(window.myForm.username.value);
...
}
Or use onsubmit method to call your submit function and stop event propogration i.e. submitting the form.

Calling Javascript on a form post to update UI via jQuery

I have an Input element that submits a form:
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
I need the button to call a javascript function, and then post the form normally.
How would that be done in jQuery?
$('#downloadButton').on('click', function (e) {
e.preventDefault();
//call your function here
$(this).parents('form').submit();
});
the preventDefault() call is important because it stops the submission of the form so you can call your function before the form submit is called at the end.
You can do:
<form onsubmit="return doSomething();">
</form>
function doSomething() {
// do something
return true;
}
If in the doSomething function you don't like what you're seeing, then return false instead of true.
EDIT
The jQuery equivalent (to satisfy both commenters): remove the onsubmit from the HTML and replace with:
jQuery(document).ready(function () {
jQuery("form#myFormId").submit(doSomething);
});
Take a look at this jsfiddle
It changes the case of textbox content to to upper case before submitting the form
$('#formID').on('submit', function () {
//var form = $(this),
//input = form.find('input[type="text"]');
//input.val(input.val().toUpperCase());
//alert(input.val());
// call your function here!
});
this is what you request:
1.- click a button (adding event handler)
2.- call a function
3.- submit form
myfunction(){
//do wathever you want
$('#formid').submit();
}
$(document).on("click", "#downloadButton", myfunction);
you can do also:
$(document).on("click", "#downloadButton", function(event){
$('#formid').submit();
});
without having an extra function
but the solution of #Paritosh is the more accurate.
jsFiddle here
Change input type to type="button" and use:
$('#downloadButton').click(function() {
//Do any javascript stuff here
//And here, etc. Then, when ready...
$('#yourFormID').submit();
});
I recommend assigning an ID attribute to your form as it is good practice.
<form id="yourFormID" action="" method="POST">
Perhaps you have only one form on this page, in that case $('form').submit() is fine. But in future (or perhaps even on this page, you haven't said) you may have multiple forms on a page and therefore the ID is necessary to specify the exact form to be submitted.
Note that if you do NOT change the submit button element's <input type="submit" to <input type="button", then you must use e.preventDefault() to prevent the button's default action. Why bother with that? Just change type="button" and use less code and less future confusion.
add a submit event on form.
$('form').submit(function(event){
event.preventDefault();
var formObj = $(this);
var formData = formObj.serialize();
$.ajax({
type: 'post',
data: formData
}).done(function(response){
console.info(response);
// update UI here accordingly.
});
});

Where to add onsubmit to a form in Javascript

In my HTML I've got a form without an onsubmit event listener:
<form action="contact.php" method="post" id="contact">
...
<input type="submit" value="Send" />
</form>
As a result, the form is always posted whenever I click the "Send" button. However, I'd like to validate the input first, so I'd like to attach an event listener and intercept the post. This is how I attach the event listener to the form:
window.onload = function() {
function validate() {
return window.confirm("Confirm");
}
var form = document.getElementById("contact");
form.addEventListener("submit", validate);
}
While the event listener is being executed, if I go by above approach the form is always posted! However, if I make the validate() function global and use onsubmit="return validate();" in the <form> tag, then the form is only being submitted conditionally, as expected.
Why does this not work by adding the validate() function as above? It seems the false return value gets lost?
Modern event handling has a more complex API, it gives more flexibility but that comes at the cost of not being able to tie behaviour to a simple boolean result.
For your use case, you need to capture the event object:
function validate(ev) {
Then you can prevent the default action on it:
if (!confirm('Confirm')) {
ev.preventDefault();
}

Disable form auto submit on button click

I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.
It's quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?
Buttons like <button>Click to do something</button> are submit buttons.
Set type="button" to change that. type="submit" is the default (as specified by the HTML spec):
The missing value default and invalid value default are the Submit Button state.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button" your form will not be submitted.
<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.
function forms_ini(){
for(var form of document.getElementsByTagName('form')){
form.addEventListener('submit', function(ev){
ev.preventDefault()
})
}
}
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}

Categories