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();});
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()};
So this has been bugging me for some time. I discovered a page that was intermittently submitting form contents twice. For simplification, the inputs are a text field and a button. Upon further inspection, I noticed one form submission included the text and button inputs and the other submission only sent the text input.
I set up a test page to troubleshoot. I put it up on jsfiddle, but I don't think it'll be much help, since I cannot see the values passed using an HTTP Proxy tool such as Fiddler.
https://jsfiddle.net/9xL5w9t2/
<form method="post" action="www.google.com" onsubmit="alert('form submitted');" id="form1" name="form1name">
<input type="submit" value="submit form" id="submitbtn1" name="submitbtn1name" />
<input type="text" id="text1" value="123" name="text1name" />
</form>
<form method="post" action="www.google.com" onsubmit="alert('form submitted');" id="form2" name="form2name">
<input type="button" value="submit form" onclick="alert('button clicked to submit form'); document.form2name.submit();" id="submitbtn2" name="submitbtn2name" />
<input type="text" id="text2" value="123" name="text2name" />
</form>
<form method="post" action="www.google.com" id="form3" name="form3name">
<input type="button" value="submit form" onclick="alert('button clicked to submit form'); document.form3name.submit();" id="submitbtn3" name="submitbtn3name" />
<input type="text" id="text3" value="123" name="text3name" />
</form>
<form method="post" action="www.google.com" onsubmit="alert('form submitted'); this.submit();" id="form4" name="form4name">
<input type="submit" value="submit form" id="submitbtn4" name="submitbtn4name" />
<input type="text" id="text4" value="123" name="text4name" />
</form>
Form 1: Submits text and button
Form 2: Submits text
Form 3: Submits text
Form 4: Submits twice. 1) Submits text 2) Submits text and button
From the looks of it, submitting using HTML Form submit sends over text and button inputs. But submitting the form using JavaScript sends over just the text input. No button.
What is the explanation for this behavior? Why does a JavaScript form submit send over text input only, yet HTML form submit sends over both text and button inputs?
Is this by design? If so, what would be the reason(s)? Seems inconsistent to have your HTML parser send the button value, yet your JS engine does not.
Thank you for any help.
Form 1: Submits text and button
.. default behavior, using a input type submit
Both input controls get submitted because you've clicked the submit button.
Add another submit-button. You will see that only the button dispatching the submit is included in the post data.
So.. what's the reason for that: This way you can add two buttongs, e.g. "cancel" and "save" to a form using the same name
Form 2: Submits text
Form 3: Submits text
.. both solutions look exactly the same to me, the input type button is not handled as an "submit input field" here.. you submit using js.
There is no action on the button and that's why it's not included. (Like described above).
Form 4: Submits twice. 1) Submits text 2) Submits text and button
You're using a input type submit like in the Form 1.. so this form gets submitted exactly the same way. But: there is also a onsubmit handler on the form that calls the submit again using js- that's the reason for the second submit.
The handler is called first, because a submit will trigger a page-reload and the script executing the event will not be "present" anymove after the submit.
The other behaviour is just like described for Fomr 2 & 3
.
Just let me know if you need some further explainations.
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;
}
So two questions here: If I use <input type="button" onclick="validate()"> then the enter key wouldn't work. However, I can use type="submit" but how would I invoke validate()?
You can have the form validate on submit, which is better anyways:
<form ... onsubmit="return validate()">
<input type="submit" />
</form>
You can return false from your validation function to prevent the form from submitting. The form will validate regardless of whether it's submitted via the return key or the button being clicked.
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.