Related
I'm writing a simple web site and would like to run some simple javascript when the user presses a button on their keyboard. Something as simple as running alert("Hello!"); or showing a modal box when the user presses enter would do.
After searching for a good while, I've only been able to find solutions that work if the page contains an input text field. Is it possible without it?
Yes, it is possible to do so, and here's how you'd do it:
document.body.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
alert("Hello! You pressed the enter key!");
}
});
Yes, you can actually use eventListener for this. For example, check out this sample page.
<html>
<body>
<script>
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
alert('You just hit enter.');
}else if(event.keyCode ==65){
alert('You just press A.');
}else if(event.keyCode==97){
alert('You just hit a.');
}else{
alert('You press something other than A, a and ENTER key');
}
})
</script>
</body>
</html>
In order to get the keycode for the various keypress you can use this:
<html>
<body>
<p>Press a key on the keyboard in the input field to get the KeyCode for that key.</p>
<input type="text" size="40" onkeypress="getKeyCode(event)">
<p id="keyCode"></p>
<script>
function getKeyCode(event) {
var x = event.which || event.keyCode;
document.getElementById("keyCode").innerHTML = "The keyCode is: " + x;
}
</script>
</body>
</html>
I have a autocomplete textbox in a form and I want to detect whether user has focussed on the textbox from navigating through tab key press.I mean tabindex has been set up on different form fields and user can navigate fields by pressing tabs.Now I want to perform some action when user directly mouse click/foxus on the textbox and some other action when user has focussed on the textbox through tab.
Below is the code I was trying.But no matter everytime code is 0.
$('#tbprofession').on('focus', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('Tabbed');
}
else
{
alert('Not tabbed');
}
});
This code does not work.
Note:Before marking duplicate it will be good if you understand the question correctly.Else I can make it more clear with more elaborated description.
Anyone can show me some light?
You can try something like that :
$(document).on("keyup", function(e) {
if ($('#tbprofession').is(":focus")) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
alert('I was tabbed!');
} else {
alert('not tabbed');
}
}
});
fiddle : https://jsfiddle.net/xc847mrp/
You can use keyup event instead:
$('#tbprofession').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 9) {
console.log('I was tabbed!', code);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input autofocus>
<input id='tbprofession'>
You could have an array of key events triggered anytime a user presses a key while on your page. Although this makes you think of a keylogger.
Or just keep the last key.
Or a boolean saying if the last key pressed was a TAB or not.
And on focus you can look at that variable.
How do you prevent an ENTER key press from submitting a form in a web-based application?
[revision 2012, no inline handler, preserve textarea enter handling]
function checkEnter(e){
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}
Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">
document.querySelector('form').onkeypress = checkEnter;
Here is a jQuery handler that can be used to stop enter submits, and also stop backspace key -> back. The (keyCode: selectorString) pairs in the "keyStop" object are used to match nodes that shouldn't fire their default action.
Remember that the web should be an accessible place, and this is breaking keyboard users' expectations. That said, in my case the web application I am working on doesn't like the back button anyway, so disabling its key shortcut is OK. The "should enter -> submit" discussion is important, but not related to the actual question asked.
Here is the code, up to you to think about accessibility and why you would actually want to do this!
$(function(){
var keyStop = {
8: ":not(input:text, textarea, input:file, input:password)", // stop backspace = back
13: "input:text, input:password", // stop enter = submit
end: null
};
$(document).bind("keydown", function(event){
var selector = keyStop[event.which];
if(selector !== undefined && $(event.target).is(selector)) {
event.preventDefault(); //stop event
}
return true;
});
});
Simply return false from the onsubmit handler
<form onsubmit="return false;">
or if you want a handler in the middle
<script>
var submitHandler = function() {
// do stuff
return false;
}
</script>
<form onsubmit="return submitHandler()">
//Turn off submit on "Enter" key
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
$("#btnSearch").attr('value');
//add more buttons here
return false;
}
});
You will have to call this function whic will just cancel the default submit behaviour of the form. You can attach it to any input field or event.
function doNothing() {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if( keyCode == 13 ) {
if(!e) var e = window.event;
e.cancelBubble = true;
e.returnValue = false;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
The ENTER key merely activates the form's default submit button, which will be the first
<input type="submit" />
the browser finds within the form.
Therefore don't have a submit button, but something like
<input type="button" value="Submit" onclick="submitform()" />
EDIT: In response to discussion in comments:
This doesn't work if you have only one text field - but it may be that is the desired behaviour in that case.
The other issue is that this relies on Javascript to submit the form. This may be a problem from an accessibility point of view. This can be solved by writing the <input type='button'/> with javascript, and then put an <input type='submit' /> within a <noscript> tag. The drawback of this approach is that for javascript-disabled browsers you will then have form submissions on ENTER. It is up to the OP to decide what is the desired behaviour in this case.
I know of no way of doing this without invoking javascript at all.
In short answer in pure Javascript is:
<script type="text/javascript">
window.addEventListener('keydown', function(e) {
if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
e.preventDefault();
return false;
}
}
}, true);
</script>
This only disables the "Enter" keypress action for input type='text'. Visitors can still use "Enter" key all over the website.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
See my detailed answer for a similar question here
I've always done it with a keypress handler like the above in the past, but today hit on a simpler solution. The enter key just triggers the first non-disabled submit button on the form, so actually all that's required is to intercept that button trying to submit:
<form>
<div style="display: none;">
<input type="submit" name="prevent-enter-submit" onclick="return false;">
</div>
<!-- rest of your form markup -->
</form>
That's it. Keypresses will be handled as usual by the browser / fields / etc. If the enter-submit logic is triggered, then the browser will find that hidden submit button and trigger it. And the javascript handler will then prevent the submision.
All the answers I found on this subject, here or in other posts has one drawback and that is it prevents the actual change trigger on the form element as well. So if you run these solutions onchange event is not triggered as well. To overcome this problem I modified these codes and developed the following code for myself. I hope this becomes useful for others.
I gave a class to my form "prevent_auto_submit" and added the following JavaScript:
$(document).ready(function()
{
$('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event)
{
if (event.keyCode == 13)
{
event.preventDefault();
$(this).trigger("change");
}
});
});
I've spent some time making this cross browser for IE8,9,10, Opera 9+, Firefox 23, Safari (PC) and Safari(MAC)
JSFiddle Example: http://jsfiddle.net/greatbigmassive/ZyeHe/
Base code - Call this function via "onkeypress" attached to your form and pass "window.event" into it.
function stopEnterSubmitting(e) {
if (e.keyCode == 13) {
var src = e.srcElement || e.target;
if (src.tagName.toLowerCase() != "textarea") {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
}
stopSubmitOnEnter (e) {
var eve = e || window.event;
var keycode = eve.keyCode || eve.which || eve.charCode;
if (keycode == 13) {
eve.cancelBubble = true;
eve.returnValue = false;
if (eve.stopPropagation) {
eve.stopPropagation();
eve.preventDefault();
}
return false;
}
}
Then on your form:
<form id="foo" onkeypress="stopSubmitOnEnter(e);">
Though, it would be better if you didn't use obtrusive JavaScript.
Preventing "ENTER" to submit form may inconvenience some of your users. So it would be better if you follow the procedure below:
Write the 'onSubmit' event in your form tag:
<form name="formname" id="formId" onSubmit="return testSubmit()" ...>
....
....
....
</form>
write Javascript function as follows:
function testSubmit(){
if(jQuery("#formId").valid())
{
return true;
}
return false;
}
(OR)
What ever the reason, if you want to prevent the form submission on pressing Enter key, you can write the following function in javascript:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
thanks.
To prevent form submit when pressing enter in a textarea or input field, check the submit event to find what type of element sent the event.
Example 1
HTML
<button type="submit" form="my-form">Submit</button>
<form id="my-form">
...
</form>
jQuery
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.type!=="submit") {
e.preventDefault();
}
});
A better solution is if you don't have a submit button and you fire the event with a normal button. It is better because in the first examlple 2 submit events are fired, but in the second example only 1 submit event is fired.
Example 2
HTML
<button type="button" onclick="$('#my-form').submit();">Submit</button>
<form id="my-form">
...
</form>
jQuery
$(document).on('submit', 'form', function(e) {
if (e.delegateTarget.activeElement.localName!=="button") {
e.preventDefault();
}
});
In my case, this jQuery JavaScript solved the problem
jQuery(function() {
jQuery("form.myform").submit(function(event) {
event.preventDefault();
return false;
});
}
You will find this more simple and useful :D
$(document).on('submit', 'form', function(e){
/* on form submit find the trigger */
if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
/* if the trigger is not between selectors list, return super false */
e.preventDefault();
return false;
}
});
How about:
<asp:Button ID="button" UseSubmitBehavior="false"/>
Add this tag to your form - onsubmit="return false;"
Then you can only submit your form with some JavaScript function.
Please check this article How to prevent ENTER keypress to submit a web form?
$(“.pc_prevent_submit”).ready(function() {
$(window).keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class=”pc_prevent_submit” action=”” method=”post”>
<input type=”text” name=”username”>
<input type=”password” name=”userpassword”>
<input type=”submit” value=”submit”>
</form>
You can trap the keydown on a form in javascript and prevent the even bubbling, I think. ENTER on a webpage basically just submits the form that the currently selected control is placed in.
This link provides a solution that has worked for me in Chrome, FF, and IE9 plus the emulator for IE7 and 8 that comes with IE9's developer tool (F12).
http://webcheatsheet.com/javascript/disable_enter_key.php
Another approach is to append the submit input button to the form only when it is supposed to be submited and replace it by a simple div during the form filling
Simply add this attribute to your FORM tag:
onsubmit="return gbCanSubmit;"
Then, in your SCRIPT tag, add this:
var gbCanSubmit = false;
Then, when you make a button or for any other reason (like in a function) you finally permit a submit, simply flip the global boolean and do a .submit() call, similar to this example:
function submitClick(){
// error handler code goes here and return false if bad data
// okay, proceed...
gbCanSubmit = true;
$('#myform').submit(); // jQuery example
}
I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted.
So I was thinking, does the enter / return button activate the first submit button in the form?
That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it.
Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values.
Just a thought.
How about:
<script>
function isok(e) {
var name = e.explicitOriginalTarget.name;
if (name == "button") {
return true
}
return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>
And just name your button right and it will still submit, but text fields i.e. the explicitOriginalTarget when you hit return in one, will not have the right name.
Here's how I'd do it:
window.addEventListener('keydown', function(event)
{
if (event.key === "Enter" && event.target.tagName !== 'TEXTAREA')
{
if(event.target.type !== 'submit')
{
event.preventDefault();
return false;
}
}
});
If none of those answers are working for you, try this. Add a submit button before the one that actually submits the form and just do nothing with the event.
HTML
<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>
JavaScript
$('#EnterKeyIntercepter').click((event) => {
event.preventDefault(); //The buck stops here.
/*If you don't know what this if statement does, just delete it.*/
if (process.env.NODE_ENV !== 'production') {
console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (⌐■_■)");
}
});
This worked for me.
onkeydown="return !(event.keyCode==13)"
<form id="form1" runat="server" onkeydown="return !(event.keyCode==13)">
</form>
put into javascript external file
(function ($) {
$(window).keydown(function (event) {
if (event.keyCode == 13) {
return false;
}
});
})(jQuery);
or somewhere inside body tag
<script>
$(document).ready(function() {
$(window).keydown(function(event) {
alert(1);
if(event.keyCode == 13) {
return false;
}
});
});
</script>
I had the same problem (forms with tons of text fields and unskilled users).
I solved it in this way:
function chkSubmit() {
if (window.confirm('Do you want to store the data?')) {
return true;
} else {
// some code to focus on a specific field
return false;
}
}
using this in the HTML code:
<form
action="go.php"
method="post"
accept-charset="utf-8"
enctype="multipart/form-data"
onsubmit="return chkSubmit()"
>
In this way the ENTER key works as planned, but a confirmation (a second ENTER tap, usually) is required.
I leave to the readers the quest for a script sending the user in the field where he pressed ENTER if he decide to stay on the form.
I have a form with a textfield inside and I am trying to disable the default behavior when the browser submits the whole form if the user presses Enter while the textfield is selected.
$('#recaptcha_response_field').keydown(function(event) { if (event.keyCode == 13) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
alert("You Press ENTER key");
return false;
}
});
Currently am getting "You Press ENTER key" and the default behavior isn't overridden.
Try this:
$(document).on("keypress", 'form', function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
This will prevent the form submit on keypress
DEMO HERE
I found this and it works for me.
<input type="text" name="somename" id="someid" value="" onkeypress="return event.keyCode!=13">
To prevent the script from blocking the enter key on other elements such as on a textarea. Change the target from "form" to "input".
$(document).on("keypress", "input", function (e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
If none of the above solution is working for you , and you are using javascript anyway , why don't you use button type as 'button' <input type='button'> and submit it using javascript
$('#form_id').submit();
U can use this script to prevent enter on entire from.
<script type="text/javascript">
$(document).on("keypress", 'form', function (e) {
if (e.target.className.indexOf("allowEnter") == -1) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
}
});
</script>
you put the classname to which control need to use enter
I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.
disableEnterKey: function disableEnterKey(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
},
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:
<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>
This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".
Here are some highlights:
It is in pure javascript (no library required).
Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
Together with the above, user can use "Enter" key anywhere else.
It is short, clean, fast and straight to the point.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
In your form tag just paste this:
onkeypress="return event.keyCode != 13;"
Example
<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">
This can be useful if you want to do search when typing and ignoring ENTER.
/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)
AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.
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.
Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)
https://www.w3.org/TR/html5/forms.html#implicit-submission
However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.
So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).
The solution is so simple:
Replace type "Submit" with button
<input type="button" value="Submit" onclick="this.form.submit()" />
this is in pure javascript
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
});
Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:
//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
if (e.which == 13) e.preventDefault();
});
Thanks to this answer: https://stackoverflow.com/a/1977126/560114.
Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form.
You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
I think setting a class to a form is much better. so I coded that:
HTML
<form class="submit-disabled">
JS
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('submit', function (e) {
e.preventDefault()
});
/**
* </End>
* Submit Disabled Form
*/
And also if you want to disable submitting only when Enter Key press:
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
e.preventDefault()
}
});
/**
* </End>
* Submit Disabled Form
*/
in HTML file:
#keypress="disableEnterKey($event)"
in js file:
disableEnterKey(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
}
First you need to disable the form on submit, but re-enable it when clicked on the button. which or keycode is not used in this case, avoiding some problems with compatibility.
let formExample = document.getElementbyId("formExample");//selects the form
formExample.addEventListener("submit", function(event){ //must be used "submit"
event.preventDefault();// prevents "form" from being sent
})
To reactivate and submit the form by clicking the button:
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateButton); //calls the function "activateButton()" on click
function activateButton(){
formExample.submit(); //submits the form
}
a variation of this would be
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateBtnConditions); //calls the function "activateBtnConditions()" on click
function activateBtnConditions(){
if(condition){
instruction
}
else{
formExample.submit()
}
}
Here is a modern, simple and reactive solution which works in:
React, Solidjs, JSX etc.
is written in Typescript
supports server-side rendering (SSR)
all modern browsers
does NOT require jQuery
blocks ALL Enter keys outside of <textarea> where you want to allow Enter
// avoids accidential form submission, add via event listener
function blockEnterKey(e: KeyboardEvent) {
if (e.key == "Enter" && !(e.target instanceof HTMLTextAreaElement)) {
e.preventDefault()
}
}
// add the event listener before the rendering return in React, etc.
if (typeof window !== undefined) {
window.addEventListener("keydown", blockEnterKey)
// the following line is for Solidjs. React has similar cleanup functionality
// onCleanup(() => document.body.removeEventListener("keydown", blockEnterKey))
}
return(
<form>
...
</form>
)
The better way I found here:
Dream.In.Code
action="javascript: void(0)" or action="return false;" (doesn't work on me)