Want HTML form submit to do nothing - javascript

I want an HTML form to do nothing after it has been submitted.
action=""
is no good because it causes the page to reload.
Basically, I want an Ajax function to be called whenever a button is pressed or someone hits Enter after typing the data. Yes, I could drop the form tag and add just call the function from the button's onclick event, but I also want the "hitting enter" functionality without getting all hackish.

By using return false; in the JavaScript code that you call from the submit button, you can stop the form from submitting.
Basically, you need the following HTML:
<form onsubmit="myFunction(); return false;">
<input type="submit" value="Submit">
</form>
Then the supporting JavaScript code:
<script language="javascript"><!--
function myFunction() {
// Do stuff
}
//--></script>
If you desire, you can also have certain conditions allow the script to submit the form:
<form onSubmit="return myFunction();">
<input type="submit" value="Submit">
</form>
Paired with:
<script language="JavaScript"><!--
function myFunction() {
// Do stuff
if (condition)
return true;
return false;
}
//--></script>

<form id="my_form" onsubmit="return false;">
is enough ...

It also works:
<form id='my_form' action="javascript:myFunction(); return false;">

<form onsubmit="return false;">

How about
<form id="my_form" onsubmit="the_ajax_call_function(); return false;">
......
</form>

You can use the following HTML
<form onSubmit="myFunction(); return false;">
<input type="submit" value="Submit">
</form>

Use jQuery. Maybe put a div around your elements from the form. Then use preventDefault() and then make your Ajax calls.

Use:
<form action='javascript:functionWithAjax("search");'>
<input class="keyword" id="keyword" name="keyword" placeholder="input your keywords" type="search">
<i class="iconfont icon-icon" onclick="functionWithAjax("search");"></i>
</form>
<script type="text/javascript">
function functionWithAjax(type) {
// Ajax action
return false;
}
</script>

In cases where 'return false' doesn't do a thing,
try just passing the event to the form's onsubmit (not action!)
and simply add event.preventDefault() in that function.
Leave the 'action' from the html. Additional info: action="javascript:etc(event)" didn't work in my tests.

As part of the button's onclick event, return false, which will stop the form from submitting.
I.e.:
function doFormStuff() {
// Ajax function body here
return false;
}
And just call that function on submit button click. There are many different ways.

You can use preventDefault to prevent the form's default submit behaviour from firing
form.addEventListener('submit', myHandler);
function myHandler(event) {
event.preventDefault();
}

Just replace 'action=""' withonsubmit='return false'. That's it.

Related

Page seems to refresh when I submit an HTML form and the console is wiped [duplicate]

I'm creating a login form and in that if any input is wrong then i want to stay on the same page and notify the client to enter the correct input
I want to stay on this page http://localhost:8080/loginpage/ but after every click i'm redirected to http://localhost:8080/loginpage/?UserName=UserName&pword=&ConfirmPassword=&Email=Email&FirstName=First+Name&LastName=Last+Name&cars=male&Signup=Signup .
I have written a code for this but it does not seem to work.
if(t!==0)
{
var er="Email-id already exists";
window.location.reload(false);
document.getElementById("nemail").value=er;
document.getElementById("username").value=username;
document.getElementById("pword").value="";
document.getElementById("confpwd").value="";
document.getElementById("fname").value=fname;
document.getElementById("lname").value=lname;
document.getElementById("gender").value=gender;
}
I have tried to use several other methods like
window.location.replace('/loginpage/');
window.location.href="/loginpage/index.html";
But none of them works.
Please help!
There are two ways to prevent a form to submit.
Set form onsubmit="return false".
Register a submit event on a from. In the callback call event.preventDefault();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>1 way to prevent form to submit via onclick attribute</h2>
<form action="#submit-from-1-way" onsubmit="return validate(this)"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<h2>2 way to prevent form to submit via submit event</h2>
<form id="form" action="#submit-from-2-way"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<script>
console.log(location.href+'#'+location.hash+'?'+location.search);
function validate(form) {
return $(form).find('input').val();
}
$('#form').submit(function (e) {
if (!validate(this)) e.preventDefault();
});
</script>
You can use preventDefault() on the click event for a given html object. This will prevent the browser from taking the default action on a specific HTML object.
For example to prevent actoin on a link:
<body>
Click Me
<script>
function dontGo(event) {
event.preventDefault();
}
document.getElementById("clickMe").addEventListener("click",dontGo);
</script>
</body>

Cannot get response from php using Ajax [duplicate]

I have an issue while using buttons inside form. I want that button to call function. It does, but with unwanted result that it refresh the page.
My simple code goes like this
<form method="POST">
<button name="data" onclick="getData()">Click</button>
</form>
On clicking the button, the function gets called with page refreshed, which resets all my previous request which affects the current page which was result of the previous request.
What should I do to prevent the page refresh?
Add type="button" to the button.
<button name="data" type="button" onclick="getData()">Click</button>
The default value of type for a button is submit, which self posts the form in your case and makes it look like a refresh.
Let getData() return false. This will fix it.
<form method="POST">
<button name="data" onclick="return getData()">Click</button>
</form>
All you need to do is put a type tag and make the type button.
<button id="btnId" type="button">Hide/Show</button>
That solves the issue
The problem is that it triggers the form submission. If you make the getData function return false then it should stop the form from submitting.
Alternatively, you could also use the preventDefault method of the event object:
function getData(e) {
e.preventDefault();
}
HTML
<form onsubmit="return false;" id="myForm">
</form>
jQuery
$('#myForm').submit(function() {
doSomething();
});
<form method="POST">
<button name="data" onclick="getData()">Click</button>
</form>
instead of using button tag, use input tag. Like this,
<form method="POST">
<input type = "button" name="data" onclick="getData()" value="Click">
</form>
If your button is default "button" make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.
if you use js do like this
<form method="POST">
<button name="data" type="button" id="btnData" onclick="getData()">Click</button>
</form>
**If you use jquery use like this**
<form method="POST">
<button name="data" type="button" id="btnData">Click</button>
</form>
$('#btnData').click(function(e){
e.preventDefault();
// Code goes here
getData(); // your onclick function call here
});
A javascript method to disable the button itself
document.getElementById("ID NAME").disabled = true;
Once all form fields have satisfied your criteria, you can re-enable the button
Using a Jquery will be something like this
$( "#ID NAME" ).prop( "disabled", true);
This one is the best solution:
<form method="post">
<button type="button" name="data" onclick="getData()">Click Me</button>
</form>
Note: My code is very simple.
For any reason in Firefox even though I have return false; and myform.preventDefault(); in the function, it refreshes the page after function runs. And I don't know if this is a good practice, but it works for me, I insert javascript:this.preventDefault(); in the action attribute .
As I said, I tried all the other suggestions and they work fine in all browsers but Firefox, if you have the same issue, try adding the prevent event in the action attribute either javascript:return false; or javascript:this.preventDefault();. Do not try with javascript:void(0); which will break your code. Don't ask me why :-).
I don't think this is an elegant way to do it, but in my case I had no other choice.
Update:
If you received an error... after ajax is processed, then remove the attribute action and in the onsubmit attribute, execute your function followed by the false return:
onsubmit="functionToRun(); return false;"
I don't know why all this trouble with Firefox, but hope this works.
Return function is not working in all the cases.
I tried this:
<button id="Reset" class="Button-class" onclick="return Reset()">Show result</button>
It didnt work for me.
I tried to return false inside the function and it worked for me.
function Reset()
{
.
.
.
return false;
}
I was facing the same problem. The problem is with the onclick function. There should not be any problem with the function getData. It worked by making the onclick function return false.
<form method="POST">
<button name="data" onclick="getData(); return false">Click</button>
</form>
I updated on #JNDPNT answer, this way the function (getData()) doesn't have to return false;
<form method="POST">
<button name="data" onclick="getData(); return false;">Click</button>
</form>
A simple issue I found is that if the function that you're trying to call is called submit, the form will be submitted either way.
You will need to rename the function for the page to not be reloaded
Add e.preventDefault(); in the starting of the function to be called when the button is clicked
Example:
const signUp = (e) => {
e.preventDefault()
try {
} catch (error) {
console.log(error.message)
}
}
The button code:
<input
type='submit'
name='submit-btn'
id='submit-btn'
value='Sign Up'
onClick={signUp}
/>
You can use ajax and jquery to solve this problem:
<script>
function getData() {
$.ajax({
url : "/urlpattern",
type : "post",
success : function(data) {
alert("success");
}
});
}
</script>
<form method="POST">
<button name="data" type="button" onclick="getData()">Click</button>
</form>

uploading a file with fetch() works but then skips both success *and* error paths [duplicate]

I have an issue while using buttons inside form. I want that button to call function. It does, but with unwanted result that it refresh the page.
My simple code goes like this
<form method="POST">
<button name="data" onclick="getData()">Click</button>
</form>
On clicking the button, the function gets called with page refreshed, which resets all my previous request which affects the current page which was result of the previous request.
What should I do to prevent the page refresh?
Add type="button" to the button.
<button name="data" type="button" onclick="getData()">Click</button>
The default value of type for a button is submit, which self posts the form in your case and makes it look like a refresh.
Let getData() return false. This will fix it.
<form method="POST">
<button name="data" onclick="return getData()">Click</button>
</form>
All you need to do is put a type tag and make the type button.
<button id="btnId" type="button">Hide/Show</button>
That solves the issue
The problem is that it triggers the form submission. If you make the getData function return false then it should stop the form from submitting.
Alternatively, you could also use the preventDefault method of the event object:
function getData(e) {
e.preventDefault();
}
HTML
<form onsubmit="return false;" id="myForm">
</form>
jQuery
$('#myForm').submit(function() {
doSomething();
});
<form method="POST">
<button name="data" onclick="getData()">Click</button>
</form>
instead of using button tag, use input tag. Like this,
<form method="POST">
<input type = "button" name="data" onclick="getData()" value="Click">
</form>
If your button is default "button" make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.
if you use js do like this
<form method="POST">
<button name="data" type="button" id="btnData" onclick="getData()">Click</button>
</form>
**If you use jquery use like this**
<form method="POST">
<button name="data" type="button" id="btnData">Click</button>
</form>
$('#btnData').click(function(e){
e.preventDefault();
// Code goes here
getData(); // your onclick function call here
});
A javascript method to disable the button itself
document.getElementById("ID NAME").disabled = true;
Once all form fields have satisfied your criteria, you can re-enable the button
Using a Jquery will be something like this
$( "#ID NAME" ).prop( "disabled", true);
This one is the best solution:
<form method="post">
<button type="button" name="data" onclick="getData()">Click Me</button>
</form>
Note: My code is very simple.
For any reason in Firefox even though I have return false; and myform.preventDefault(); in the function, it refreshes the page after function runs. And I don't know if this is a good practice, but it works for me, I insert javascript:this.preventDefault(); in the action attribute .
As I said, I tried all the other suggestions and they work fine in all browsers but Firefox, if you have the same issue, try adding the prevent event in the action attribute either javascript:return false; or javascript:this.preventDefault();. Do not try with javascript:void(0); which will break your code. Don't ask me why :-).
I don't think this is an elegant way to do it, but in my case I had no other choice.
Update:
If you received an error... after ajax is processed, then remove the attribute action and in the onsubmit attribute, execute your function followed by the false return:
onsubmit="functionToRun(); return false;"
I don't know why all this trouble with Firefox, but hope this works.
Return function is not working in all the cases.
I tried this:
<button id="Reset" class="Button-class" onclick="return Reset()">Show result</button>
It didnt work for me.
I tried to return false inside the function and it worked for me.
function Reset()
{
.
.
.
return false;
}
I was facing the same problem. The problem is with the onclick function. There should not be any problem with the function getData. It worked by making the onclick function return false.
<form method="POST">
<button name="data" onclick="getData(); return false">Click</button>
</form>
I updated on #JNDPNT answer, this way the function (getData()) doesn't have to return false;
<form method="POST">
<button name="data" onclick="getData(); return false;">Click</button>
</form>
A simple issue I found is that if the function that you're trying to call is called submit, the form will be submitted either way.
You will need to rename the function for the page to not be reloaded
Add e.preventDefault(); in the starting of the function to be called when the button is clicked
Example:
const signUp = (e) => {
e.preventDefault()
try {
} catch (error) {
console.log(error.message)
}
}
The button code:
<input
type='submit'
name='submit-btn'
id='submit-btn'
value='Sign Up'
onClick={signUp}
/>
You can use ajax and jquery to solve this problem:
<script>
function getData() {
$.ajax({
url : "/urlpattern",
type : "post",
success : function(data) {
alert("success");
}
});
}
</script>
<form method="POST">
<button name="data" type="button" onclick="getData()">Click</button>
</form>

How to display an alert after checking the input from? [duplicate]

I need to select a form via native javascript (not jQuery) and prevent the form submission (preventDefault).
The trick is that the form does not have a name or id, and cannot be assigned one.
My HTML:
<div id="search">
<form method="get">
<input type="text" name="post"/>
<input type="submit" value="Post">
</form>
</div>
So far, I have tried to use document.forms[0] and document.getElementsByTagName("form")[0] to select the form, but the value returned is undefined.
Another possible solution is to overload the functionality of the submit button, but I did not have success with that either.
Using querySelector and an event listener, it's almost like jQuery
document.querySelector('#search form').addEventListener('submit', function(e) {
e.preventDefault();
});
note that the script has to come after the elements, or use a DOM ready handler, so the elements are available.
FIDDLE
Simple way is use onsubmit event handler
<script>
var submitHandler = function() {
// your code
return false;
}
</script>
<form method="get" onsubmit="return submitHandler()">....</form>
or more easy
<form onsubmit="return false;">
on form submit just return false.
e.g. <form onsubmit="return false">

Stop form submit with native javascript

I need to select a form via native javascript (not jQuery) and prevent the form submission (preventDefault).
The trick is that the form does not have a name or id, and cannot be assigned one.
My HTML:
<div id="search">
<form method="get">
<input type="text" name="post"/>
<input type="submit" value="Post">
</form>
</div>
So far, I have tried to use document.forms[0] and document.getElementsByTagName("form")[0] to select the form, but the value returned is undefined.
Another possible solution is to overload the functionality of the submit button, but I did not have success with that either.
Using querySelector and an event listener, it's almost like jQuery
document.querySelector('#search form').addEventListener('submit', function(e) {
e.preventDefault();
});
note that the script has to come after the elements, or use a DOM ready handler, so the elements are available.
FIDDLE
Simple way is use onsubmit event handler
<script>
var submitHandler = function() {
// your code
return false;
}
</script>
<form method="get" onsubmit="return submitHandler()">....</form>
or more easy
<form onsubmit="return false;">
on form submit just return false.
e.g. <form onsubmit="return false">

Categories