Related
If the user press enter key, it should behave as he is pressing the esc key.
function OnEditorKeyPress(editor, e) {
if (e.htmlEvent.keyCode == 13) {
e.htmlEvent.keyCode = 27;
//treeList.CancelEdit();
}
}
But the value 13 remains same after e.htmlEvent.keyCode = 27; this statement also. How to assign a new value or any other alternative method is there to do this?
These properties of the event object are read only (including KeyCode), so you can't do such of thing. Why you can't do something like this?
function OnEditorKeyPress(editor, e) {
//If user press enter or escape
if (e.htmlEvent.keyCode == 13 || e.htmlEvent.keyCode == 27) // correct comparison operation
{
treeList.CancelEdit();
e.htmlEvent.preventDefault
}
}
EDIT: If you insist, read this on the Mozilla Forums: Need to override key pressed replacing keycode
Hi this code helps you in stopping the default functionality of "Enter" button However you can enter your code to do whatever you want when user press "enter". Though Implementing ESC functionality on ENTER will not be appreciated.
Here is working example http://jsfiddle.net/Z4dgr/11/
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function displayunicode(e){
e.preventDefault();
var unicode=e.keyCode? e.keyCode : e.charCode
alert(unicode)
}
</script>
<form>
Enter from keyboard <input type="text" size="2" maxlength="1" onkeypress="displayunicode(event); this.select()" />
</form>
</body>
</html>
According to Tom's answer here is what you need.
function OnEditorKeyPress(editor, e) {
//If user press enter or escape
if (e.htmlEvent.keyCode == 13 || e.htmlEvent.keyCode = 27)
{
treeList.CancelEdit();
e.htmlEvent.preventDefault();
}
}
How to do that?
I tried:
var key = event.which || event.keyCode || event.charCode;
if(key == 8) alert('backspace');
but it doesn't work...
If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that
my code:
$('#content').bind('input', function(event){
var text = $(this).val(),
key = event.which || event.keyCode || event.charCode;
if(key == 8){
// here I want to ignore backspace and del
}
// here I'm doing my stuff
var new_text = 'bla bla'+text;
$(this).val(new_text);
});
no character should be appended in my input, besides what I'm adding with val()
actually the input from the user should be completely ignored, only the key pressing action is important to me
Use .onkeydown and cancel the removing with return false;. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
keydown with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
Mozilla Docs
Supported Browsers
Have you tried using 'onkeydown'?
This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
InputEvent.inputType can be used for Backspace detection Mozilla Docs.
It works on Chrome desktop, Chrome Android and Safari iOS.
<input type="text" id="test" />
<script>
document.getElementById("test").addEventListener('input', (event) => {
console.log(event.inputType);
// Typing of any character event.inputType = 'insertText'
// Backspace button event.inputType = 'deleteContentBackward'
// Delete button event.inputType = 'deleteContentForward'
})
</script>
on android devices using chrome we can't detect a backspace.
You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
//Here's one example, not sure what your application is but here is a relevant and likely application
function addDashesOnKeyUp()
{
var tb = document.getElementById("tb1");
var key = event.which || event.keyCode || event.charCode;
if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) )
{
tb.value += "-"
}
}
Live demo
Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">
<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
if (event.keyCode == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.keyCode == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
};
//jquery code
$('#inpu').on('keydown', function(e) {
if (event.which == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.which == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
});
</script>
I have this code
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
regex=/[1-9]/;
if(regex.test(keycode))
return true;
else
void(0);
}
in the html I added an input and I add the onkeydown event onkeydown="verifyKey(event);"
I like to verify the key before it display on the text
If the key is a number or coma(,) or full stop(.)
then accept the key
else
refuse it
Thanks
Here in your code you are testing the regular expression defined with the keycode, so every chearactes on the keyboard will be allowed since the keycode of every key is numbers, so you will not get the result what you expect. Instead of using the regular expression try the below code
<html>
<head>
<script type="text/javascript">
function verifyKey(e)
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if((keycode>=48 && keycode<=57))
{alert("if")
return true;
}
else if((keycode == 188)||(keycode == 190))
{alert("elseif");
return true;
}
else
{alert("else")
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeypress="return verifyKey(event)" />
</body>
</html>
I'm using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY rejects all other key inputs, like ctrl-A to select the text, or even any other browser functions like ctrl-T or ctrl-W while the text box is selected. Does anyone know of a better script to only allow numerical input, but not block normal commands (that aren't being directly input into the field)? Thanks
Here is the code I'm using now:
function numbersonly(e, decimal)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
return true;
else if ((("0123456789").indexOf(keychar) > -1))
return true;
else if (decimal && (keychar == "."))
return true;
else
return false;
}
Edit: None of the solutions provided have solved my problem of allowing commands like ctrl-A while the text box is selected. That was the whole point of my asking here, so I have gone back to using my original script. Oh well.
This is something I made another time for just numbers, it will allow all the formatters as well.
jQuery
$('input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
Try it
http://jsfiddle.net/zpg8k/
As a note, you'll want to filter on submit/server side as well, for sake of pasting/context menu and browsers that don't support the paste event.
Edit to elaborate on multiple methods
I see you're bouncing around the 'accepted' answer, so I'll clear something up. You can really use any of the methods listed here, they all work. What I'd personally do is use mine for live client side filtering, and then on submit and server side use RegEx as suggested by others. However, no client side by itself will be 100% effective as there is nothing stopping me from putting document.getElementById('theInput').value = 'Hey, letters.';
in the console and bypassing any clientside verification (except for polling, but I could just cancel the setInterval from the console as well). Use whichever client side solution you like, but be sure you implement something on submit and server side as well.
Edit 2 - #Tim Down
Alright, per the comments I had to adjust two things I didn't think of. First, keypress instead of keydown, which has been updated, but the lack of indexOf in IE (seriously Microsoft!?) breaks the example above as well. Here's an alternative
$('input').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!($.inArray(k,a)>=0))
e.preventDefault();
});
New jsfiddle: http://jsfiddle.net/umNuB/
This works in IE, Chrome AND Firefox:
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" />
.keypress(function(e)
{
var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];
if (!($.inArray(e.which, key_codes) >= 0)) {
e.preventDefault();
}
});
You need Backspace and Delete keys too ;)
http://jsfiddle.net/PgHFp/
<html>
<head>
<title>Test</title>
<script language="javascript">
function checkInput(ob) {
var invalidChars = /[^0-9]/gi
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars,"");
}
}
</script>
</head>
<body>
<input type="text" onkeyup="checkInput(this)"/>
</body>
</html>
Just use regex to get rid of any non number characters whenever a key is pressed or the textbox loses focus.
var numInput;
window.onload = function () {
numInput = document.getElementById('numonly');
numInput.onkeydown = numInput.onblur = numInput.onkeyup = function()
{
numInput.value = numInput.value.replace(/[^0-9]+/,"");
}
}
The only event that contains information about the character typed is keypress. Anything character-related you may infer from the keyCode property of keydown or keyup events is unreliable and dependent on a particular keyboard mapping. The following will prevent non-numeric keyboard input all major browsers by using the character obtained from the keypress event. It won't prevent the user from pasting or dragging non-numeric text in.
var input = document.getElementById("your_input");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (!evt.ctrlKey && !evt.metaKey && !evt.altKey) {
var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
if (charCode && !/\d/.test(String.fromCharCode(charCode))) {
return false;
}
}
};
I use this:
oEl.keypress(function(ev)
{
var sKey = String.fromCharCode(ev.which);
if (!sKey.match(/[0-9]/) || !sKey === "")
ev.preventDefault();
});
The advantage is, that every key which does not provide an input to the field is still allowed, so you don't have to worry about every single special key. Even combos like CTRL + R do still work.
EDIT
As this is not working in Firefox I had to modify the function a little:
oEl.keypress(function(ev)
{
var iKeyCode = ev.which || ev.keyCode;
var aSpecialKeysForFirefox = [8, 9, 13, 27, 37, 38, 39, 40, 46];
var sKey = String.fromCharCode(iKeyCode);
if (sKey !== "" && $.inArray(iKeyCode, aSpecialKeysForFirefox ) < 0 && !sKey.match(/[0-9]/)) {
ev.preventDefault();
}
});
Explanation
All Browsers handle jquerys keypress event differently. To make it work in FF the $.inArray check is added. As firefoxs keypress-event doesn't trigger when combinations like strg+tab are used, but the others do, the key.match approach still adds a little value to the latter, as it enables those combinations.
Maybe you are using bootstrap. If so, this may suffice:
<input type="text" data-mask="9999999">
Input mask
The following code is something I use extensively. I found the script in a forum, but modified and expanded it to accommodate my needs:
<script type="text/javascript">
// Restrict user input in a text field
// create as many regular expressions here as you need:
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;
var usernameOnly = /[0-9A-Za-z\._-]/g;
function restrictInput(myfield, e, restrictionType, checkdot){
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if user pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if the user presses other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
if(checkdot == "checkdot"){
return !isNaN(myfield.value.toString() + character);
} else {
return true;
}
} else {
return false;
}
}
}
</script>
Different usage methods would be:
<!-- To accept only alphabets -->
<input type="text" onkeypress="return restrictInput(this, event, alphaOnly);">
<!-- To accept only numbers without dot -->
<input type="text" onkeypress="return restrictInput(this, event, digitsOnly);">
<!-- To accept only numbers and dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly);">
<!-- To accept only numbers and only one dot -->
<input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');">
<!-- To accept only characters for a username field -->
<input type="text" onkeypress="return restrictInput(this, event, usernameOnly);">
Add <script type="text/javascript" src="jquery.numeric.js"></script> then use
$("element").numeric({ decimal: false, negative: false });
shorter way and easy to understand:
$('#someID').keypress(function(e) {
var k = e.which;
if (k <= 48 || k >= 58) {e.preventDefault()};
});
This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.
JSFiddle - decimal number input
// Allow only decimal number input
$('#decimalInput').keypress(function (e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
// allow a max of 1 decimal point to be entered
if (this.value.indexOf(".") === -1) {
a.push(46);
}
if (!(a.indexOf(k) >= 0)) e.preventDefault();
$('span').text('KeyCode: ' + k);
});
I know that there are already many answers but for the sake of simplicity i would like to add another answer which is simple and self explanatory in which we do not have to remember keycodes and it also works across all browsers.
document.getElementById('myinput').onkeydown = function(e)
{
console.log(e.key);
//console.log(e.target.value);
switch (e.key)
{
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
case "0":
case "Backspace":
return true;
break;
case ".":
if (e.target.value.indexOf(".") == -1)
{
return true;
}
else
{
return false;
}
break;
default:
return false;
}
}
<input type="text" placeholder="Enter Value" id="myinput" />
It's worth pointing out that no matter how tightly you manage to control this via the front end (Javascript, HTML, etc), you still need to validate it at the server, because there's nothing to stop a user from turning off javascript, or even deliberately posting junk to your form to try to hack you.
My advice: Use the HTML5 markup so that browsers which support it will use it. Also use the JQuery option previously suggested (the inital solution may have flaws, but it seems like the comments have been working through that). And then do server-side validation as well.
this will enable the numpad inputs also.
.keydown(function(event){
if(event.keyCode == 8 || event.keyCode == 46)
return true;
if(event.keyCode >= 96 && event.keyCode <= 105)
return true;
if(isNaN(parseInt(String.fromCharCode(event.keyCode),10)))
return false;
});
In order to block anything but numbers from being input into a text field but still allowing for other buttons to work (such as delete, shift, tab, etc.) look at a reference of the Javascript key codes; anything from 65 on up (to 222) can be blocked.
Using Jquery and Javascript, that would look like:
$('#textFieldId').keydown(function(event) {
if ( event.keyCode > 64 ) {
event.preventDefault();
}
});
The key codes will be the same in Javascript whether or not Jquery is used.
Here is my solution: a combination of the working ones below.
var checkInput = function(e) {
if (!e) {
e = window.event;
}
var code = e.keyCode || e.which;
if (!e.ctrlKey) {
//46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
return true;
//35..39 - home, end, left, right
if (code >= 35 && code <= 39)
return true;
//numpad numbers
if (code >= 96 && code <= 105)
return true;
//keyboard numbers
if (isNaN(parseInt(String.fromCharCode(code), 10))) {
e.preventDefault();
return false;
}
}
return true;
};
I came across your question while trying to figure this out myself. Here is the solution that I came up with.
// Prevent user from entering non-numeric characters in number boxes.
(function (inputs) {
var input;
var f = function (e) {
var unicodeRe = /U\+(\d+)/;
// Chrome doesn't support the standard key property, so use keyIdentifier instead.
// Instead of the actual character that "key" returns, keyIdentifier returns
// A string such as "U+004F" representing the unicode character.
// For special characters (e.g., "Shift", a string containing the name of the key is returned.)
var ch = e.key || e.keyIdentifier;
var match = ch.match(unicodeRe);
// keyIdentifier returns a unicode. Convert to string.
if (match) {
ch = String.fromCharCode(Number.parseInt(match[1], 16));
}
console.log(ch);
if (ch.length === 1 && /[^0-9]/.test(ch)) {
if (!/[\b]/.test(ch)) { // Don't prevent backspace.
e.preventDefault();
}
}
};
for (var i = 0, l = inputs.length; i < l; i += 1) {
input = inputs[i];
input.onkeydown = f;
}
}(document.querySelectorAll("input[type=number],#routeFilterBox")));
Edit: I've discovered that my solution does not allow the user to enter numbers via the numpad in Chrome. The 0-9 keypad keys seem to be returning the character "`" for 0 and A-I for the rest of the number keys.
All of the answers are outdated, lengthy and will cause annoyance to your users. Most of them don’t even filter or allow pasted content.
Instead of filtering the input, do some validation before submitting the form and then also server-side.
HTML has validation included:
<input type="number" pattern="[0-9]+">
This also enables the number keyboard on mobile.
This is my plugin for that case:
(function( $ ) {
$.fn.numbers = function(options) {
$(this).keypress(function(evt){
var setting = $.extend( {
'digits' : 8
}, options);
if($(this).val().length > (setting.digits - 1) && evt.which != 8){
evt.preventDefault();
}
else{
if(evt.which < 48 || evt.which > 57){
if(evt.keyCode != 8){
evt.preventDefault();
}
}
}
});
};
})( jQuery );
Use:
$('#limin').numbers({digits:3});
$('#limax').numbers();
There is my current solution of numeric input, need to test in different browsers but seems to work
Support comma and period delimiter (czech native is comma), space and numpad/keyboard numbers input. Allow Ctrl+C Ctrl+A or Ctrl+X, arrow navigation and delete block Ctrl+V. React on escape key by blurring input.
Watch my Coffee script:
(($) ->
$.fn.onlyNumbers = ->
#each ->
$(#).keydown (e) ->
# get code of key
code = if e.keyCode then e.keyCode else e.which
return $(#).blur() if code is 27 # blur on escape
return if code in [46, 8, 9, 13] # 46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
return if (e.ctrlKey or e.metaKey) and code in [65, 67, 88] # ctrl|command + [a, c, x]
return if code in [96..105] # numpad numbers
return if code in [48..57] # numbers on keyboard
return if code in [35..39] # 35..39 - home, end, left, right
return if code in [188, 190, 32] # comma, period, space
return if code in [44] # comma, period,
e.returnValue = false # IE hate you
e.preventDefault();
$(#).keypress (e) ->
code = if e.keyCode then e.keyCode else e.which
return if code in [44, 46, 32] # comma, period, space
return if code in [48..57] # numbers on keyboard
e.returnValue = false # IE hate you
e.preventDefault();
) jQuery
You can get compiled Javascript here http://goo.gl/SbyhXN
My functions:
$('.input_integer_only').on('input', function(e) {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
$('.input_float_only').on('input', function(e) {
var $var = $(this).val().replace(/[^0-9\.]/g, '');
var $aVar = $var.split('.');
if($aVar.length > 2) {
$var = $aVar[0] + '.' + $aVar[1];
}
$(this).val($var);
});
You can make changes to accept the keycode for Ctrl keys: 17, 18, 19, 20.
Then your code will be like:
function numbersonly(e, decimal) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) || (key==17) || (key==18) || (key==19) || (key==20))
return true;
else if ((("0123456789").indexOf(keychar) > -1))
return true;
else if (decimal && (keychar == "."))
return true;
else
return false;
}
document.getElementById('myinput').onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8
|| e.keyCode == 9)) {
return false;
}
}
You can do like this to accept only Numbers in text Box,
function onChange(event){
var ckeckChars = /[^0-9]/gi;
if(checkChars.test(event.target.value)) {
event.target.value = event.target.value.replace(ckeckChars,"");
}
I am using below in Angular to restrict character
in HTML
For Number Only
<input
type="text"
id="score"
(keypress) ="onInputChange($event,'[0-9]')"
maxlength="3"
class="form-control">
for Alphabets Only
<input
type="text"
id="state"
(keypress) ="onInputChange($event,'[a-zA-Z]')"
maxlength="3"
class="form-control">
In TypeScript
onInputChange(event: any, inpPattern:string): void {
var input = event.key;
if(input.match(inpPattern)==null){
event.preventDefault();
}
}
This JavaScript function will be used to restrict alphabets and
special characters in Textbox , only numbers, delete, arrow keys and
backspace will be allowed. JavaScript Code Snippet - Allow Numbers
in TextBox, Restrict Alphabets and Special Characters
Tested in IE & Chrome.
JavaScript function
<script type="text/javascript">
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var flag = false;
var x = e.which || e.keycode;
if ((x >= 48 && x <= 57) || x == 8 ||
(x >= 35 && x <= 40) || x == 46)
flag = true;
else
flag = false;
if (flag && e.keyCode === 46 && $(e.currentTarget).val().split('.').length === 2) {
flag = false;
}
return flag;
}
</script>
HTML Source Code with JavaScript
<html>
<head>
<title>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</title>
<script type="text/javascript">
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
</script>
</head>
<body style="text-align: center;">
<h1>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</h1>
<big>Enter numbers only: </big>
<input type="text" onkeypress='return restrictAlphabets(event)'/>
</body>
</html>
Refrence
You can handle te event on html by introducing keypresshandler function
function keypresshandler(event)
{
var charCode = event.keyCode;
//You condition
if (charCode == 58 ){
event.preventDefault();
return false;
}
}
Javascript is often used on the browser client side to perform simple tasks that would otherwise require a full postback to the server. Many of those simple tasks involve processing text or characters entered into a form element on a web page, and it is often necessary to know the javascript keycode associated with a character. Here is a reference.
Press a key in the text box below to see the corresponding Javascript key code.
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '48') && (charCode <= '57')) || (charCode == '44')) {
return true;
}
else {
return false;
}
}
Enter Text:
<input type="text" id="number" onkeypress="return restrictCharacters(event);" />
I'm looking to create a form where pressing the enter key causes focus to go to the "next" form element on the page. The solution I keep finding on the web is...
<body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}">
Unfortunately, that only seems to work in IE. So the real meat of this question is if anybody knows of a solution that works for FF and Chrome? Additionally, I'd rather not have to add onkeydown events to the form elements themselves, but if that's the only way, it will have to do.
This issue is similar to question 905222, but deserving of it's own question in my opinion.
Edit: also, I've seen people bring up the issue that this isn't good style, as it diverges from form behavior that users are used to. I agree! It's a client request :(
I used the logic suggested by Andrew which is very effective. And this is my version:
$('body').on('keydown', 'input, select', function(e) {
if (e.key === "Enter") {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
KeyboardEvent's keycode (i.e: e.keycode) depreciation notice :- https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
The simplest vanilla JS snippet I came up with:
document.addEventListener('keydown', function (event) {
if (event.keyCode === 13 && event.target.nodeName === 'INPUT') {
var form = event.target.form;
var index = Array.prototype.indexOf.call(form, event.target);
form.elements[index + 1].focus();
event.preventDefault();
}
});
Works in IE 9+ and modern browsers.
Map [Enter] key to work like the [Tab] key
I've rewritten Andre Van Zuydam's answer, which didn't work for me, in jQuery. This caputures both Enter and Shift+Enter. Enter tabs forward, and Shift+Enter tabs back.
I've also rewritten the way self is initialized by the current item in focus. The form is also selected that way. Here's the code:
// Map [Enter] key to work like the [Tab] key
// Daniel P. Clark 2014
// Catch the keydown for the entire document
$(document).keydown(function(e) {
// Set self as the current item in focus
var self = $(':focus'),
// Set the form by the current item in focus
form = self.parents('form:eq(0)'),
focusable;
// Array of Indexable/Tab-able items
focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
function enterKey(){
if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
// If not a regular hyperlink/button/textarea
if ($.inArray(self, focusable) && (!self.is('a,button'))){
// Then prevent the default [Enter] key behaviour from submitting the form
e.preventDefault();
} // Otherwise follow the link/button as by design, or put new line in textarea
// Focus on the next item (either previous or next depending on shift)
focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
return false;
}
}
// We need to capture the [Shift] key and check the [Enter] key either way.
if (e.shiftKey) { enterKey() } else { enterKey() }
});
The reason textarea
is included is because we "do" want to tab into it. Also, once in, we don't want to stop the default behavior of Enter from putting in a new line.
The reason a and button
allow the default action, "and" still focus on the next item, is because they don't always load another page. There can be a trigger/effect on those such as an accordion or tabbed content. So once you trigger the default behavior, and the page does its special effect, you still want to go to the next item since your trigger may have well introduced it.
Thank you for the good script.
I have just added the shift event on the above function to go back between elements, I thought someone may need this.
$('body').on('keydown', 'input, select, textarea', function(e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
, prev
;
if (e.shiftKey) {
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
prev = focusable.eq(focusable.index(this)-1);
if (prev.length) {
prev.focus();
} else {
form.submit();
}
}
}
else
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
This worked for me:
$(document).on('keydown', ':tabbable', function(e) {
if (e.key === "Enter") {
e.preventDefault();
var $canfocus = $(':tabbable:visible');
var index = $canfocus.index(document.activeElement) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
Changing this behaviour actually creates a far better user experience than the default behaviour implemented natively. Consider that the behaviour of the enter key is already inconsistent from the user's point of view, because in a single line input, enter tends to submit a form, while in a multi-line textarea, it simply adds a newline to the contents of the field.
I recently did it like this (uses jQuery):
$('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
if (e.keyCode==13) {
var focusable = $('input,a,select,button,textarea').filter(':visible');
focusable.eq(focusable.index(this)+1).focus();
return false;
}
});
This is not terribly efficient, but works well enough and is reliable - just add the 'enterastab' class to any input element that should behave in this way.
I reworked the OPs solution into a Knockout binding and thought I'd share it. Thanks very much :-)
Here's a Fiddle
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script>
</head>
<body>
<div data-bind="nextFieldOnEnter:true">
<input type="text" />
<input type="text" />
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" />
<input type="text" />
</div>
<script type="text/javascript">
ko.bindingHandlers.nextFieldOnEnter = {
init: function(element, valueAccessor, allBindingsAccessor) {
$(element).on('keydown', 'input, select', function (e) {
var self = $(this)
, form = $(element)
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
var nextIndex = focusable.index(this) == focusable.length -1 ? 0 : focusable.index(this) + 1;
next = focusable.eq(nextIndex);
next.focus();
return false;
}
});
}
};
ko.applyBindings({});
</script>
</body>
</html>
Here is an angular.js directive to make enter go to the next field using the other answers as inspiration. There is some, perhaps, odd looking code here because I only use the jQlite packaged with angular. I believe most of the features here work in all browsers > IE8.
angular.module('myapp', [])
.directive('pdkNextInputOnEnter', function() {
var includeTags = ['INPUT', 'SELECT'];
function link(scope, element, attrs) {
element.on('keydown', function (e) {
// Go to next form element on enter and only for included tags
if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
// Find all form elements that can receive focus
var focusable = element[0].querySelectorAll('input,select,button,textarea');
// Get the index of the currently focused element
var currentIndex = Array.prototype.indexOf.call(focusable, e.target)
// Find the next items in the list
var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;
// Focus the next element
if(nextIndex >= 0 && nextIndex < focusable.length)
focusable[nextIndex].focus();
return false;
}
});
}
return {
restrict: 'A',
link: link
};
});
Here's how I use it in the app I'm working on, by just adding the pdk-next-input-on-enter directive on an element. I am using a barcode scanner to enter data into fields, the default function of the scanner is to emulate a keayboard, injecting an enter key after typing the data of the scanned barcode.
There is one side-effect to this code (a positive one for my use-case), if it moves focus onto a button, the enter keyup event will cause the button's action to be activated. This worked really well for my flow as the last form element in my markup is a button that I want activated once all the fields have been "tabbed" through by scanning barcodes.
<!DOCTYPE html>
<html ng-app=myapp>
<head>
<script src="angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-controller="LabelPrintingController">
<div class='.container' pdk-next-input-on-enter>
<select ng-options="p for p in partNumbers" ng-model="selectedPart" ng-change="selectedPartChanged()"></select>
<h2>{{labelDocument.SerialNumber}}</h2>
<div ng-show="labelDocument.ComponentSerials">
<b>Component Serials</b>
<ul>
<li ng-repeat="serial in labelDocument.ComponentSerials">
{{serial.name}}<br/>
<input type="text" ng-model="serial.value" />
</li>
</ul>
</div>
<button ng-click="printLabel()">Print</button>
</div>
</body>
</html>
Try this...
$(document).ready(function () {
$.fn.enterkeytab = function () {
$(this).on('keydown', 'input,select,text,button', function (e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select').filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
//if disable try get next 10 fields
if (next.is(":disabled")){
for(i=2;i<10;i++){
next = focusable.eq(focusable.index(this) + i);
if (!next.is(":disabled"))
break;
}
}
next.focus();
}
return false;
}
});
}
$("form").enterkeytab();
});
I've had a similar problem, where I wanted to press + on the numpad to tab to the next field. Now I've released a library that I think will help you.
PlusAsTab: A jQuery plugin to use the numpad plus key as a tab key equivalent.
Since you want enter/↵ instead, you can set the options. Find out which key you want to use with the jQuery event.which demo.
JoelPurra.PlusAsTab.setOptions({
// Use enter instead of plus
// Number 13 found through demo at
// https://api.jquery.com/event.which/
key: 13
});
// Matches all inputs with name "a[]" (needs some character escaping)
$('input[name=a\\[\\]]').plusAsTab();
You can try it out yourself in the PlusAsTab enter as tab demo.
function return2tab (div)
{
document.addEventListener('keydown', function (ev) {
if (ev.key === "Enter" && ev.target.nodeName === 'INPUT') {
var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
let ol= div.querySelectorAll(focusableElementsString);
for (let i=0; i<ol.length; i++) {
if (ol[i] === ev.target) {
let o= i<ol.length-1? ol[i+1]: o[0];
o.focus(); break;
}
}
ev.preventDefault();
}
});
}
I have it working in only JavaScript. Firefox won't let you update the keyCode, so all you can do is trap keyCode 13 and force it to focus on the next element by tabIndex as if keyCode 9 was pressed. The tricky part is finding the next tabIndex. I have tested this only on IE8-IE10 and Firefox and it works:
function ModifyEnterKeyPressAsTab(event)
{
var caller;
var key;
if (window.event)
{
caller = window.event.srcElement; //Get the event caller in IE.
key = window.event.keyCode; //Get the keycode in IE.
}
else
{
caller = event.target; //Get the event caller in Firefox.
key = event.which; //Get the keycode in Firefox.
}
if (key == 13) //Enter key was pressed.
{
cTab = caller.tabIndex; //caller tabIndex.
maxTab = 0; //highest tabIndex (start at 0 to change)
minTab = cTab; //lowest tabIndex (this may change, but start at caller)
allById = document.getElementsByTagName("input"); //Get input elements.
allByIndex = []; //Storage for elements by index.
c = 0; //index of the caller in allByIndex (start at 0 to change)
i = 0; //generic indexer for allByIndex;
for (id in allById) //Loop through all the input elements by id.
{
allByIndex[i] = allById[id]; //Set allByIndex.
tab = allByIndex[i].tabIndex;
if (caller == allByIndex[i])
c = i; //Get the index of the caller.
if (tab > maxTab)
maxTab = tab; //Get the highest tabIndex on the page.
if (tab < minTab && tab >= 0)
minTab = tab; //Get the lowest positive tabIndex on the page.
i++;
}
//Loop through tab indexes from caller to highest.
for (tab = cTab; tab <= maxTab; tab++)
{
//Look for this tabIndex from the caller to the end of page.
for (i = c + 1; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == tab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Look for the next tabIndex from the start of page to the caller.
for (i = 0; i < c; i++)
{
if (allByIndex[i].tabIndex == tab + 1)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
//Continue searching from the caller for the next tabIndex.
}
//The caller was the last element with the highest tabIndex,
//so find the first element with the lowest tabIndex.
for (i = 0; i < allByIndex.length; i++)
{
if (allByIndex[i].tabIndex == minTab)
{
allByIndex[i].focus(); //Move to that element and stop.
return;
}
}
}
}
To use this code, add it to your html input tag:
<input id="SomeID" onkeydown="ModifyEnterKeyPressAsTab(event);" ... >
Or add it to an element in javascript:
document.getElementById("SomeID").onKeyDown = ModifyEnterKeyPressAsTab;
A couple other notes:
I only needed it to work on my input elements, but you could extend it to other document elements if you need to. For this, getElementsByClassName is very helpful, but that is a whole other topic.
A limitation is that it only tabs between the elements that you have added to your allById array. It does not tab around to the other things that your browser might, like toolbars and menus outside your html document. Perhaps this is a feature instead of a limitation. If you like, trap keyCode 9 and this behavior will work with the tab key too.
You can use my code below, tested in Mozilla, IE, and Chrome
// Use to act like tab using enter key
$.fn.enterkeytab=function(){
$(this).on('keydown', 'input, select,', function(e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
alert("wd");
//form.submit();
}
return false;
}
});
}
How to Use?
$("#form").enterkeytab(); // enter key tab
If you can I would reconsider doing this: the default action of pressing <Enter> while in a form submits the form and anything you do to change this default action / expected behaviour could cause some usability issues with the site.
Vanilla js with support for Shift + Enter and ability to choose which HTML tags are focusable. Should work IE9+.
onKeyUp(e) {
switch (e.keyCode) {
case 13: //Enter
var focusableElements = document.querySelectorAll('input, button')
var index = Array.prototype.indexOf.call(focusableElements, document.activeElement)
if(e.shiftKey)
focus(focusableElements, index - 1)
else
focus(focusableElements, index + 1)
e.preventDefault()
break;
}
function focus(elements, index) {
if(elements[index])
elements[index].focus()
}
}
Here's what I came up with.
form.addEventListener("submit", (e) => { //On Submit
let key = e.charCode || e.keyCode || 0 //get the key code
if (key = 13) { //If enter key
e.preventDefault()
const inputs = Array.from(document.querySelectorAll("form input")) //Get array of inputs
let nextInput = inputs[inputs.indexOf(document.activeElement) + 1] //get index of input after the current input
nextInput.focus() //focus new input
}
}
Many answers here uses e.keyCode and e.which that are deprecated.
Instead you should use e.key === 'Enter'.
Documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
I'm sorry but I can't test these snippets just now. Will come back later after testing it.
With HTML:
<body onkeypress="if(event.key==='Enter' && event.target.form){focusNextElement(event); return false;}">
With jQuery:
$(window).on('keypress', function (ev)
{
if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev)
}
And with Vanilla JS:
document.addEventListener('keypress', function (ev) {
if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev);
});
You can take focusNextElement() function from here:
https://stackoverflow.com/a/35173443/3356679
Easiest way to solve this problem with the focus function of JavaScript as follows:
You can copy and try it # home!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input id="input1" type="text" onkeypress="pressEnter()" />
<input id="input2" type="text" onkeypress="pressEnter2()" />
<input id="input3" type="text"/>
<script type="text/javascript">
function pressEnter() {
// Key Code for ENTER = 13
if ((event.keyCode == 13)) {
document.getElementById("input2").focus({preventScroll:false});
}
}
function pressEnter2() {
if ((event.keyCode == 13)) {
document.getElementById("input3").focus({preventScroll:false});
}
}
</script>
</body>
</html>
I had a problem to use enter key instead of Tab in React js .The solution of anjana-silva is working fine and just some small issue for input date and autocomplete as I am using MUI . So I change it a bit and add arrow keys (left/right) as well .
install jquery using npm
npm install jquery --save
write the below in App.js If you want to have this behavior In the whole of your application
import $ from 'jquery';
useEffect(() => {
$('body').on('keydown', 'input, select,button', function (e) {
if (e.keyCode === 13 || e.keyCode === 39) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,a,select,button,textarea').filter(':visible:not([readonly]):enabled');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
}
return false;
}
if (e.keyCode === 37) {
var self = $(this), form = self.parents('form:eq(0)'), focusable, prev;
focusable = form.find('input,a,select,button,textarea').filter(':visible:not([readonly]):enabled');
prev = focusable.eq(focusable.index(this) - 1);
if (prev.length) {
prev.focus();
}
return false;
}
});
}, []);
I had a simular need.
Here is what I did:
<script type="text/javascript" language="javascript">
function convertEnterToTab() {
if(event.keyCode==13) {
event.keyCode = 9;
}
}
document.onkeydown = convertEnterToTab;
</script>
In all that cases, only works in Chrome and IE, I added the following code to solve that:
var key = (window.event) ? e.keyCode : e.which;
and I tested the key value on if keycode equals 13
$('body').on('keydown', 'input, select, textarea', function (e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
var key = (window.event) ? e.keyCode : e.which;
if (key == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
} else {
focusable.click();
}
return false;
}
});
$("#form input , select , textarea").keypress(function(e){
if(e.keyCode == 13){
var enter_position = $(this).index();
$("#form input , select , textarea").eq(enter_position+1).focus();
}
});
You could programatically iterate the form elements adding the onkeydown handler as you go. This way you can reuse the code.