I know this question has been asked before but I could not find a satisfactory answer for my situation. So I am asking again.
I have a simple form with 2 text boxes and a submit button. After the user enters text in either text box they should not be able to submit through the Enter key, only the submit button should allow them to submit. I thought trapping the enter keypress and returning false from the onChange event handler would do the trick but apparently not, this still causes a form submission...
function doNotSubmit(element) {
alert("I told you not to, why did you do it?");
return false;
}
</script>
<form id="myForm" action="MyBackEnd.aspx" method="post">
<table>
<tbody>
<tr>
<td>
Joe: <input id="JoeText" type="text" onChange="doNotSubmit(this)">
</td>
<td>
Schmoe: <input id="SchmoeText" type="text" onChange="doNotSubmit(this)" >
</td>
</tr>
</tbody>
</table>
<input type=submit>
I tested on both Chrome and FF (latest versions).
Can you please show me how to prevent the form submission?
Thanks.
to piggy back on #Dasein's anwser you want to prevent the default behavior instead of stopping propagation ( i.e. returning false):
document.getElementById("myForm").onkeypress = function(e) {
var key = e.charCode || e.keyCode || 0;
if (key == 13) {
alert("I told you not to, why did you do it?");
e.preventDefault();
}
}
<form id="myForm" action="MyBackEnd.aspx" method="post">
<table>
<tbody>
<tr>
<td>
Joe: <input id="JoeText" type="text">
</td>
<td>
Schmoe: <input id="SchmoeText" type="text" >
</td>
</tr>
</tbody>
</table>
<input type=submit>
I think this should do:
document.getElementById("myInput").onkeypress = function(e) {
var key = e.charCode || e.keyCode || 0;
if (key == 13) {
alert("I told you not to, why did you do it?");
return false;
}
}
If you include a submit button then the default form behavior is to submit on enter key. To prevent accidental submissions you could add a confirm dialog to the onsubmit event (form A). Another alternative is to replace the submit button with your own (form B). However, the user would then need to click the button to submit.
Run snippet to test
(Tested in Chrome, Firefox, and IE 5-11)
<html>
<body>
Form A: This form submits on enter key
<form action="handler.aspx" method="post" onsubmit="return confirm('submit form?')">
<input type="text" >
<input type="text" >
<input type="submit">
</form>
<p>
Form B: This form submits only on button click<br>
<form action="hanlder.aspx" method="post" >
<input type="text" >
<input type="text" >
<input type="button" value="submit" onclick="if (confirm('Submit form?')) document.forms[1].submit()">
</form>
</body>
</html>
I am surprised no one has given a solution that achieves the desired effect of preventing accidental submission by hitting enter on a text field without also preventing intentional submission by hitting enter while the submit button has the focus.
To this end, I recommend:
function submitFunction(e)
{
if(document.activeElement!=document.getElementById('submit')) e.preventDefault();
}
The lazy solution, which works but often results in code that is less extensible or more work to maintain, is to put this in the onsubmit attribute of the <form> element. Often a better solution is to use addEventListener to add the function as a listener to the form element:
document.getElementById('myForm').addEventListener('submit', submitFunction);
Regardless of which method you choose to invoke the function, in your HTML make sure to give an ID to the submit button:
<input type="submit" id="submit" />
I prefer this solution because it allows the expected behavior of allowing the user to submit the form by tabbing through the form and then pressing enter when the submit button is highlighted, and it also allows clicking on the submit button, because that element will have the focus in both these cases, but it prevents accidental submission because the submit element will not have the focus in these cases.
This is an improvement for accessibility which can be important for disabled users, users using a text-only console browser, users without a mouse, and can still be marked improvement for users with a mouse that is unreliable or inconvenient. It happens more than you might realize. Plus, some users just like being able to navigate this way, so not breaking this behavior is an improvement in user experience.
How about below code snippet
<form method="POST">
<div style="display: none;">
<input type="submit" name="prevent-enter-submit" onclick="return false;">
</div>
</form>
For those using react:
<form
onSubmit={handleSubmit(onSubmit)}
onKeyDown={e => {
if (e.key === 'Enter') {
// Keeps form from submiting on hitting enter
e.preventDefault();
}
}}
>
Related
I'm only using HTML and JavaScript.
I have one form
<form id="form1">
<input name="name" type="text" size="20">
</form>
And one button
<button onclick="outputname()" type="submit">Search</button>
So the idea is the user types a number on the form and clicks the search button and an action is performed (this works great).
However, if the user enters a number and hits the Enter button on keyboard the page is refreshed. The same happens on iPad. ("Return" button is displayed instead of "Go").
So I want the Enter button to work on keyboard and Go to work on iOS.
The idea is that the user enters a customer number and the relevant details are displayed.
Give an ID to both your input field and button, to be sure you trap the correct one:
HTML:
<form action="destination.html" method="post">
<input id="foo" name="name" type="text" size="20">
<button id="mybutt" onclick="outputname()" type="submit">Search</button>
</form>
Note that destination.html is where you want the data posted to. If you want it posted to the same file, just use: action="" or leave it out.
Javascript:
document.getElementById('foo').onkeypress = function(e){
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){
var btn = document.getElementById('mybutt');
mybutt.click();
return false;
}
}
Sources:
How to detect when the user presses Enter in an input field
Capturing the Enter key to cause a button click with javascript
Insert this:
action="post"
Inside your form tag. I.e., your form tag will have to be this way
<form id="form1" action="post">
In this case, you could manage the submit event, instead of key/click events.
<form id="form1" onsubmit="outputname()">
Submission events triggered by either a click or pressing enter will call outputname.
i'm using button key for my project but this is not work when i push Enter Key.
why 'enter key' not working in this form?
<form action="" method="post">
<input type="text" >
<input type="button" >
</form>
how this is work with javascript, plz help me
i will not sue type="submit"
It seems you want implicit submission:
A form element's default button is the first submit
button in tree order whose form owner is that
form element.
If the user agent supports letting the user submit a form implicitly
(for example, on some platforms hitting the "enter" key while a text
field is focused implicitly submits the form), then doing so for a
form whose default button has a defined activation behavior
must cause the user agent to run synthetic click activation steps
on that default button.
Therefore, the button must be a submit button, not a button in button state:
<input type="submit">
I think an <input type="submit"> is what you want :)
$(form).on('submit', function{
//do whatever you want...
})
<form action="raftel">
<input name="name" type="text"/>
<input name="password" type="password"/>
<input type="submit"/>
</form>
I have a form, In this form there is only one text field. after the field is filled user pressing enter key. but the form is not submit in ie8 how to fix this.
But it works fine with chrome and firefox.
example code :
<form>
<label><input type="text" /></label>
<input value="Enter after adding value" type="submit">
</form>
how to make ie to work on enter key pressed.
thanks in advance!
Some browsers by default allow the enter key to submit a form, others do not.
You can work around this by adding an event handler that will submit the form on enter key. Try something like
$("input").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
$("form").submit();
}
});
If you have multiple forms on the page, then ensure you add an id attribute and update the above code accordingly.
There you go
<form id="myForm">
<label><input type="text" /></label>
<input value="Enter after adding value" type="submit" id="name">
</form>
<script type="text/javascript">
$(document).ready(function()
{
$("#name").keypress(function(e)
{
if(e.which==13){
document.getElementById("myForm").submit();
}
});
});
I hope that I could help
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'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.