I got this code right here which executes the function validate() when submit is clicked. The function changes some of the text in the page. But I can't see the effect because the page automatically refreshes after submission:
<form name="myForm" onsubmit="validate(); return false;">
Age: <input type="text" name="age" />
Height (meters): <input type="text" name="height" />
Weight (kilograms): <input type="text" name="weight" />
<input type="submit" value="Submit">
</form>
How do I prevent the page from reloading after each submission?
You can use a test button inside your form
<input type="button" value="Test button" onclick="validate();">
Once solved, remove the button.
You can also use Firebug (or equivalent) to add a breakpoint in your javascript code.
The submit event fired by your form automatically initiates the form action. If no form action is declared, it refreshes the page. Your need to prevent this default action from occuring before validation, then submit the data after it has passed validation.
Add preventDefault() to your validation code.
Make sure you add return false; in your validate() function.
That will prevent the form to be submitted.
Example :
function validate() {
//Validation code goes here
return false;
}
Related
I need to connect one button to 2 activities, in this case the form argument "action" and button argument "onclick" inside a form.
The forms "action" is PHP-based class and the button's "onclick" is connected to a javascript.
Environment:
The question is generic but to clarify I will use the form in later stage in a Laravel 8 environment. This means that the handling of form "action" is being taken care of by Laravel through a route. The onclick should be triggered and the javascript is physically positioned at the end of the Laravel blade view.
The problem:
I noticed that having the button inside the form, runs the form "action", but prevents the button argument "onclick" to trigger the javascript. If put the mentioned button outside of form, then one can trigger the form, and the button outside the form but ends up with need of 2 buttons which break simplifying the user flow.
Question:
How can I trigger both form "action" and the javascript function from one button? Note! It is not needed that javascript is being trigger by "onclick" if there are other ways to trigger the javascript.
Test-1: Basic form
<form
method="post"
action="/payment-checkout"
>
<button type="button" name="button" onclick="initCheckout()">Send</button>
</form>
Result test-1:
forms action is being executed, but not javascript.
Test-2: Attempt to solve problem using form attribute "onsubmit":
<form
id="myForm"
method="post"
action="/payment-checkout"
onsubmit="submitFormFromJavascriptFunction()"
>
<input type="submit" name="" value="Submit">
</form>
function submitFormFromJavascriptFunction() {
// Execute this...
}
document.getElementById("myForm").onsubmit = function() {submitFormFromJavascriptFunction()};
Result test-2:
forms action is being executed, but not javascript.
Try to trigger sumbit event on a button click manually by using
document.getElementById("myForm").submit();
from your onclick function
Example
function submitform() {
console.log('Inside the onclick function');
document.getElementById("myForm").submit();
}
<form action="/action_page.php" id="myForm">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<button type="button" onclick="submitform()">Submit</button>
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p>
Below is an example of doing a conventional html form submit with javascript execution on submit of the form.
The form gets submitted based on the return value of the javascript function.
Javascript function is attached to onsubmit event of the form.
button is a normal submit button with no event handler attached to itself.
//this function getts called on submission of the form via submit button.
//Its return value dictates whether form will be submitted or not
function checkQuery(){
var query = document.getElementById('myQuery');
if(query.value==""){
alert("Please enter your search query")
return false; //form will not submit
}
return true;//form will get submitted and laravel will see that submit button was pressed
}
<form
method="get"
action="https://stackoverflow.com/search" onsubmit="return checkQuery();"
>
<input type="text" id="myQuery" name="q" placeholder="your search query here">
<button type="submit" name="button">Search Now</button>
</form>
Your Test 2 should be like this:
<form
id="myForm"
method="post"
action="/payment-checkout"
onsubmit="return submitFormFromJavascriptFunction()"
>
<input type="submit" name="" value="Submit">
</form>
function submitFormFromJavascriptFunction() {
console.log("submitFormFromJavascriptFunction is getting called");
return true // or false based on your logic
}
// no need for below line
//document.getElementById("myForm").onsubmit = function() //{submitFormFromJavascriptFunction()};
I'm doing some validation on a HTML form using min and max attributes. I also want to prevent form submission if the submit button is clicked once to prevent multiple form submissions before a page is reloaded.
Here's the inline code for disabling the button:
<input type="submit" name="name" value="REGISTER" onclick="this.disabled=true;this.form.submit();">
Here's the number input field code:
<input type="number" name="endNo" placeholder="END" min="5" max="20">
If I include the inline JS for the submit button, the min and max validation doesn't work. When removed, it seems to work just fine. Why is this happening and how can I satisfy both conditions, disable the button once clicked while still validating the min and max values for the number input field?
I'm using google chrome.
The submit method on form element does what it promises, it just submits the form, doesn't do a validation. You can manually do validation with the checkValidity method.
<input type="submit" name="name" value="REGISTER"
onclick="if(this.form.checkValidity()){this.disabled=true;this.form.submit();}">
I'm doing some validation on a HTML form using min and max attributes. I also want to prevent form submission if the submit button is clicked once to prevent multiple form submissions before a page is reloaded.
As you said, you want to prevent form submission, so you must point your bullets to the <form> tag. When you need to handle the submit event, always attack the <form>, so let's add an onsubmit attribute:
<form method="post" action="my-script.php" onsubmit="return something();">
Now let's add a little funtion which tells to our <form> what to do. In this case let's show the result from the input:
<script type="text/javascript">
function something() {
var v = document.getElementById( "endNo" ).value;
alert( "The value is " + v );
return false;
}
</script>
I added some id attribute to the input to be handled by javascript:
<input type="number" id="endNo" name="endNo" placeholder="END" min="5" max="20">
The submit button only shows the disabled event in the onclick attribute because return false is already being executed on the <form> tag:
<input type="submit" name="name" value="REGISTER" onclick="this.disabled=true;">
The whole tag looks like this:
<script type="text/javascript">
function something() {
var v = document.getElementById( "endNo" ).value;
alert( "The value is " + v );
return false;
}
</script>
<form method="post" action="" onsubmit="return something();">
<input type="number" id="endNo" name="endNo" placeholder="END" min="5" max="20">
<input type="submit" name="name" value="REGISTER" onclick="this.disabled=true;">
</form>
See it in action: https://jsfiddle.net/darioferrer/mfs3adqm/
Check some similar cases:
On submit form, return false not working
onSubmit after checking return false and still submit
Why does my HTML form still submit when I return false from onsubmit?
It would seem this.form.submit() is bypassing the the min/max checks even if you do it in the console (getting form by id then calling submit). I don't think this has to do with your setup.
Try this approach
<form>
<input type="number" id="endNo" name="endNo" placeholder="END" min="5" max="20" required> <!-- I assume it is required? -->
<input type="button" id="fakeSubmit" name="name" value="REGISTER" onclick="submitIfValid()"> <!-- fake submit -->
<input type="submit" id="submitButton" style="visibility:hidden"> <!-- Actual submit -->
</form>
<script>
function submitIfValid()
{
if(document.getElementById('endNo').value < document.getElementById('endNo').getAttribute("min") || document.getElementById('endNo').value > document.getElementById('endNo').getAttribute("max")) // Get the attributes dynamically and check
{
document.getElementById('submitButton').click(); // Simulate a standard click to show error
}
else
{
document.getElementById('fakeSubmit').disabled = true; // Disabled it, we got our value
document.getElementById('submitButton').click(); // Actual submission
}
}
</script>
Make sure you add your server side checks. NEVER trust jQuery or javascript
Note: If left blank, it would be < than the min
Note 2: If you are open minded towards jQuery, the form validation becomes a lot easier ($(formid).valid()) which makes it easier than my approach and in case of multiple fields to check. You can read about it here.
You could change the input type from submit to button to stop it from submitting right away.
<input type="button" name="name" value="REGISTER" onclick="this.disabled='true';this.form.submit();" />
i want to only validate the form and don't want to submit it, so that i can use the form values in modifying other part of the same html page by calling a function "myfunction()" after form validation. for this i want to use a button suggest me required code.my code is following :-
<form name="form1">
<input type="text" name="name1" required></input>
<button onclick="myfunction()" ></button> // i want to validation of form by this button
</form>
You can try this by setting onsubmit event of form to return false; as follows:
<form name="form1" onsubmit="return false;">
<input type="text" name="name1" required></input>
<button onclick="myfunction();" ></button>
</form>
This will not submit the form on clicking the button but will execute myfunction() instead.
If you know jQuery, then you can do this as follows:
$('form[name="form1"]').submit(function (event) {
// This will prevent form being submitted.
event.preventDefault();
// Call your function.
myfunction();
});
For maintainability consider adding an event listener to the button by selection instead of inline. When the button is clicked an event object is passed to the callback. Event objects have a number of properties and methods. In this case you're looking for the method "preventDefault" which prevents the default action of the event which in this case is a form submit. An example:
<form name="form1">
<input type="text" name="name1" required />
<button id="my-button"></button>
</form>
document.getElementById('my-button').addEventListener('click', function(e){
e.preventDefault();
var form = document.forms['form1']; //or this.parentNode
//do stuff
}, false);
i have achived this goal by modifying code as follow:-
<form name="form1" onsubmit="myfunction();return false;">
<input type="text" name="name1" required></input>
<button >check form and call function</button>
</form>
by this i am able to check form and call my function and form is also not submitted in this case.
now i want to reset the form without clicking any button. suggest javascript code for this.
HTML form validation by input type button, not by submit.
Try this
<form name="form1" onsubmit="myfunction(); return false;">
<input type="text" name="name1" required></input>
<button type="submit">Submit</button>
</form>
I have an html form that I want to only submit from a button located outside my form. I am using javascript to perform some verification and do not want the form to submit unless my javascript functions succeed. I found that if I have the button inside the form it will always submit regardless of the javascript, but if I have it outside the form when a user presses enter it simply submits the form. How can I force enter to perform the button javascript instead of submitting?
<form name="form1" action=<?$_SERVER["PHP_SELF"].'?'.$_SERVER["QUERY_STRING"]?> method="post">
<input type="text" maxlength="5" size="5" name="frmZip" value="">
<input type="hidden" name="frmLat" value="200">
<input type="hidden" name="frmLng" value="200">
<input type="submit" disabled="disabled" style="display:none" />
</form>
<button type="button" id="GetCoordinates" onclick="doClick();">Find Stores</button>
EDIT:
Found my solution.
I changed from
</form>
<button type="button" id="GetCoordinates" onclick="doClick();">Find Stores</button>
to
<input type="button" name="frmSubmit" onclick="doClick();" value="Submit">
</form>
This prevented the button from submitting the form so I submitted it in my doClick() via javascript.
EDIT 2:
While this seemed to work for a time, it has stopped catching the enter keystroke. I updated my button to:
<input type="submit" name="frmSubmit" onclick="return doClick();" value="Find Stores">
And always returned false in doClick(). This allowed me to submit the form via javascript once everything had executed.
While this doesn't answer your direct question, you can actually keep the button and simply use your validation on the form submit:
<form onsubmit="return validateForm()">
Then, in your validateForm method, return true or false indicating whether or not the validation has passed.
However to answer your direct question, you can also use the same approach on the submit button which will prevent the form from being submitted.
Update
As pointed out in the comments, an unontrusive solution is often desirable so here's that:
document.getElementById('theForm').onsubmit = function() { return validateForm(); };
Your button inside the form will not submit the form on enter if you add preventDefault...
$("form").submit(function(e) {e.preventDefault();});
I have an input text box and a search submit button, and when user clicks the Search submit button, I want to redirect user to url http://testsearch/results.aspx?k=<value of text box k>, for example, if user put "StackOverflow" into text box and then clicks the search button, I want to redirect user to the following page,
http://testsearch/results.aspx?k=StackOverflow
I find when I use button for Search button, it works (see below source codes),
<input type="text" id="k" name="k" />
<input type="button" id="Go" value="Search" onclick="location.href = 'http://somemachine/Search/results.aspx?k='+document.getElementById('k').value;"/>
but when I use submit for Search button, it does not works (see below source codes), why?
<input type="text" id="k" name="k" />
<input type="submit" id="Go" value="Search" onclick="location.href = 'http://somemachine/Search/results.aspx?k='+document.getElementById('k').value;"/>
thanks in advance,
George
You can even use the submit button this way:
<input type="submit" id="Go" value="Search" onclick="document.location='http://testsearch/results.aspx?k=StackOverflow'; return false;" />
Semantically submit button is used to submit forms not redirect pages. You should use normal button type for this. However as i showed you can use the submit button too but that is not semantic i think.
The below line prevents the form from being submitted.
return false;
That is what you are missing in your code :)
Thanks
<button>-elements and <input type="button"/> don't do anything by default, unless you tell them to do something with Javascript.
<input type="submit"/> will submit the form it is in.
So, if <input type="submit"/> won't work, you got it probably not in the <form/>-element itself.
If that's the only field in your form, simply set the form's method to "get" and it'll work.
<html>
<body>
<form action="http://localhost/mytest" method="get" >
<input type="text" id="k" name="k" />
<input type="submit" id="Go" value="Search" />
</form>
</body>
</html>
<button> means "put a button in the page and do whatever the onclick event says". So if you don't write an onclick handler the page doesn't do nothing.
If you use submit is ok, because you want to redirect to another page.
If you want to use button anyway you can do this way:
<script>
function doTheSearch() {
// do the submit mannually
document.getElementById('myForm').submit();
}
</script>
<form id="myForm" action="results.aspx">
<input type="text" id="k" name="k" />
<input type="button" id="Go" value="Search" onclick="doTheSearch();" />
</form>
Warning: submit button with onclick
If you have a submit button (inside a form, it is, a working submit button) with an onclick event, some browsers will:
1) execute onclick
2) execute submit
your onclick tries to redirect but the submit button wins.
If you want to avoid it you have some options:
a) change submit button to normal button
b) avoid the submit thing (add onsubmit="return false;" to form element)
c) use the submit procedure (form action="..." method="get", no onclick event), the browser will be happy and you can control the submit in the onsubmit event (you can cancel it or not).
make sure you got the input's in a form tag with a GET method:
<form action='http://testsearch/results.aspx' method='GET'>
... inputs
</form>
If I'm understanding correctly, it is not working because it is not in a form tag. If you put it in a form tag with method="get" it should work. The button works because it does not have to be in a form.