Enter key press behaves like a Tab in Javascript - javascript

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.

Related

Check if Tab key is held down

I want to check if the Tab key is pressed and held down and released so that I can perform some other actions with other key combinations.
var shifted = false;
var tabbed = false;
$(document).on('keyup keydown', function(e) {
shifted = e.shiftKey;
tabbed = e.keyCode === 9;
console.log(tabbed);
});
The above code is working fine for the Shift key, but it's not working for the Tab key. When the Tab key is pressed and held the tabbed variable should be true and when released it should be false.
To answer the question (rather than question if the question should be a question):
This MDN page describes how keyboard events work.
one keydown, with repeat = false
multiple keydown, with repeat = true
one keyup
So you can check for when the tab is started to be held down with keydown && !repeat and when it's stopped being held down with keyup
Note you must also cancel the event so that it doesn't do the correct/expected behaviour of tabbing to the next tabbed-indexed input (emphasis on what tab actually should be doing...)
It's also cleaner to keep the events separate, giving:
var tabdown = false;
$(document).on('keydown', function(e) {
if (e.keyCode === 9) {
tabdown = true;
return false;
}
if (tabdown && e.keyCode >= 49 && e.keyCode <= 51)
{
$("#in" + (e.keyCode-48)).focus();
return false;
}
});
$(document).on('keyup', function(e) {
if (e.keyCode === 9) tabdown = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<em>hold tab and 1, 2 or 3 to change inputs</em><br/>
<input type='text' id='in1'>
<input type='text' id='in2'>
<input type='text' id='in3'>
But you'll note that an instruction is needed on the page as it's not a normal method - and also disables the normal method to easily/quickly switch between inputs in order.
This is not a recommended course of action.
But included here for completeness.
Use the following to identify is tabbed
tabbed = (e.keyCode === 9 && e.type === 'keydown')?true:false;

jQuery: selectionStart returns undefined

Situation
browser
Google Chtome 69
html
<textarea id="message" name="message">
// input some messsage
</textarea>
js(jQuery)
$(function () {
$("#message").on("keydown keyup keypress change", function () {
//this part runs correctly
})
$('#message').on('keydown', function (e) {
if ((e.wich && e.wich === 13) || (e.keyCode && e.keyCode === 13)) {
var $textarea = $(this);
var sentence = $textarea.val();
var position = $textarea.selectionStart;
var length = sentence.length;
var before = sentence.substr(0, position);
var after = sentence.substr(position, length);
sentence = before + "\n" + after;
}
});
});
When I input something in the #message textarea and push Enter key in the area, nothing would happen. According to Chrome developer tool, selectionStart method seems to return Undefined.
Needs
Enter key has been made disabled in this form page in order to avoid submitting the data mitakenly.
js
function fnCancelEnter()
{
if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
if (window.event.keyCode == 13)
{
return false;
}
}
return true;
}
However, in this textarea, I want to enable user to add a break line by pressing Enter key.
I'm sorry but I don't have much knowledge about jQuery and javascript. Please tell me how to do.
Please replace $textarea.selectionStart by $textarea.get(0).selectionStart. Then try again.

How to replace code to use RegExp

I have the following code which checks for "enter" key as well as prevent the use of > and < sign in the textbox.
<script type="text/javascript" language="javascript">
function checkKeycode(e) {
var keycode;
if (window.event) // IE
keycode = e.keyCode;
else if (e.which) // Netscape/Firefox/Opera
keycode = e.which;
if (keycode == 13) {
//Get the button the user wants to have clicked
var btn = document.getElementById(btnSearch);
if (btn != null) { //If we find the button click it
btn.click();
event.keyCode = 0
}
//Removed when above code was added 12-09-13
//CallSearch();
}
}
function CallSearch() {
var objsearchText = window.document.getElementById('txtSearchText');
var searchText;
if ((objsearchText!=null))
{
searchText = objsearchText.value;
searchText = searchText.replace(/>/gi, " >");
searchText = searchText.replace(/</gi, "< ");
objsearchText.value = searchText;
}
//This cookie is used for the backbutton to work in search on postback
//This cookie must be cleared to prevent old search results from displayed
document.cookie='postbackcookie=';
document.location.href="search_results.aspx?searchtext=";
}
</script>
How can I shorten the code to be more effecient and use the onBlur function and to use RegExp instead of replace? Or is replace a faster method than RegExp?
You are saying that you want to prevent < and > chars. Here is an easier way, just ignore these chars when the keydown event occurs on them.
Also I suggest to use jQuery - if you can.
http://api.jquery.com/event.which/
var ignoredChars = [188, 190]; // <, >
$('#myTextField').keydown(function(e) {
if(ignoredChars.indexOf(e.which) > -1) {
e.preventDefault();
e.stopPropagation();
return false;
}
})
.keyup(function(e) {
if(e.which === 13) {
$('#searchButton').click();
}
});
Just add this event handler to your textbox and remove the regexp replacements.
If you don't want characters to be input by user, surpress them as early as possible. This way you won't get in trouble fiddling them out of a big string later.

Focus the next input with down arrow key (as with the tab key)

I have a huge entry form and fields for the users to input.
In the form user use tab key to move to next feild,there are some hidden fields and readonly textboxes in between on which tab key is disabled using javascript.
Now users finds difficult to use tab key and wants same functionality on down arrow key of the keyboard.
I was using the below code to invoke the tab key code on js but not working,please some body help me on this.
function handleKeyDownEvent(eventRef)
{
var charCode = (window.event) ? eventRef.keyCode : eventRef.which;
//alert(charCode);
// Arrow keys (37:left, 38:up, 39:right, 40:down)...
if ( (charCode == 40) )
{
if ( window.event )
window.event.keyCode = 9;
else
event.which = 9;
return false;
}
return true;
}
<input type="text" onkeydown=" return handleKeyDownEvent(event);" >
Using jQuery, you can do this :
$('input, select').keydown(function(e) {
if (e.keyCode==40) {
$(this).next('input, select').focus();
}
});
When you press the down arrow key (keyCode 40), the next input receives the focus.
DEMO​
EDIT :
In Vanilla JS, this could be done like this :
function doThing(inputs) {
for (var i=0; i<inputs.length; i++) {
inputs[i].onkeydown = function(e) {
if (e.keyCode==40) {
var node = this.nextSibling;
while (node) {
console.log(node.tagName);
if (node.tagName=='INPUT' || node.tagName=='SELECT') {
node.focus();
break;
}
node = node.nextSibling;
}
}
};
};
}
doThing(document.getElementsByTagName('input'));
doThing(document.getElementsByTagName('select'));
Note that you'd probably want to map the up key too, and go to first input at last one, etc. I let you handle the details depending on your exact requirements.
This is my final working code:
$('input[type="text"],textarea').keydown( function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 40) {
e.preventDefault();
var inputs = $(this).parents('form').find(':input[type="text"]:enabled:visible:not("disabled"),textarea');
inputs.eq( inputs.index(this)+ 1 ).focus();
inputs.eq( inputs.index(this)+ 1 ).click();
}
});
If I understand correctly, some fields are read-only, so the tab key still activates them, even though they are read-only, and this is annoying, as you have to press the tab key perhaps several times to get to the next editable field. If that is correct, then an alternate solution would be to use the tabindex attribute on your input fields, indexing each one so that the read-only and otherwise non-editable fields aren't selected. You can find more info on the tabindex attribute here.

Cycle Focus to First Form Element from Last Element & Vice Versa

I have created a form with malsup's Form Plugin wherein it submits on change of the inputs. I have set up my jQuery script to index drop down menus and visible inputs, and uses that index to determine whether keydown of tab should move focus to the next element or the first element, and likewise with shift+tab keydown. However, instead of moving focus to the first element from the last element on tab keydown like I would like it to, it moves focus to the second element. How can I change it to cycle focus to the actual first and last elements? Here is a live link to my form: http://www.presspound.org/calculator/ajax/sample.php. Thanks to anyone that tries to help. Here is my script:
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
var shiftDown = false;
$('input, select').each(function (i) {
$(this).data('initial', $(this).val());
});
$('input, select').keyup(function(event) {
if (event.keyCode==16) {
shiftDown = false;
$('#shiftCatch').val(shiftDown);
}
});
$('input, select').keydown(function(event) {
if (event.keyCode==16) {
shiftDown = true;
$('#shiftCatch').val(shiftDown);
}
if (event.keyCode==13) {
$('#captured').val(event.target.id);
} else if (event.keyCode==9 && shiftDown==false) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var nextEl = fields.eq(index+1).attr('id');
var firstEl = fields.eq(0).attr('id');
var focusEl = '#'+firstEl;
if (index>-1 && (index+1)<fields.length) {
$('#captured').val(nextEl);
} else if(index+1>=fields.length) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(firstEl);
} else {
event.preventDefault();
$(focusEl).focus();
}
}
return false;
});
} else if (event.keyCode==9 && shiftDown==true) {
return $(event.target).each(function() {
var fields = $(this).parents('form:eq(0),calculator').find('select, input:visible');
var index = fields.index(this);
var prevEl = fields.eq(index-1).attr('id');
var lastEl = fields.eq(fields.length-1).attr('id');
var focusEl = '#'+lastEl;
if (index<fields.length && (index-1)>-1) {
$('#captured').val(prevEl);
} else if (index==0) {
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(lastEl);
} else {
event.preventDefault();
$(focusEl).select();
}
}
return false;
});
}
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 100 );
}
}
Edit #1: I made a few minor changes to the code, which has brought me a little closer to my intended functionality of the script. However, I only made one change to the code pertaining to the focus: I tried to to disable the tab keydown when pressed on the last element (and also the shift+tab keydown on the first element) in an attempt to force the focus on the element I want without skipping over it like it has been doing. This is the code I added:
$(this).one('keydown', function (event) {
return !(event.keyCode==9 && shiftDown==true);
});
This kind of works. After the page loads, If the user presses tab on the last element without making a change to its value, the focus will be set to the second element. However, the second time the user presses tab on the last element without making a change to its value, and every subsequent time thereafter, the focus will be set to the first element, just as I would like it to.
Edit #2: I replaced the code in Edit #1, with code utilizing event.preventDefault(), which works better. While if a user does a shift+tab keydown when in the first element, the focus moves to the last element as it should. However, if the user continues to hold down the shift key and presses tab again, focus will be set back to the first element. And if the user continues to hold the shift key down still yet and hits tab, the focus will move back to the last element. The focus will shift back and forth between the first and last element until the user lifts the shift key. This problem does not occur when only pressing tab. Here is the new code snippet:
event.preventDefault();
$(focusEl).focus();
You have a lot of code I didn't get full overview over, so I don't know if I missed some functionality you wanted integrated, but for the tabbing/shift-tabbing through form elements, this should do the work:
var elements = $("#container :input:visible");
var n = elements.length;
elements
.keydown(function(event){
if (event.keyCode == 9) { //if tab
var currentIndex = elements.index(this);
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
if (el.attr("type") == "text")
elements.eq(newIndex).select();
else
elements.eq(newIndex).focus();
event.preventDefault();
}
});
elements will be the jQuery object containing all the input fields, in my example it's all the input fields inside the div #container
Here's a demo: http://jsfiddle.net/rA3L9/
Here is the solution, which I couldn't have reached it without Simen's help. Thanks again, Simen.
$(document).ready(function() {
var options = {
target: '#c_main',
success: setFocus
};
$('#calculator').live('submit', function() {
$(this).ajaxSubmit(options);
return false;
});
$(this).focusin(function(event) {
$('#calculator :input:visible').each(function (i) {
$(this).data('initial', $(this).val());
});
return $(event.target).each(function() {
$('#c_main :input:visible').live(($.browser.opera ? 'keypress' : 'keydown'), function(event){
var elements = $("#calculator :input:visible");
var n = elements.length;
var currentIndex = elements.index(this);
if (event.keyCode == 13) { //if enter
var focusElement = elements.eq(currentIndex).attr('id');
$('#captured').val(focusElement);
} else if (event.keyCode == 9) { //if tab
var newIndex = event.shiftKey ? (currentIndex - 1) % n : (currentIndex + 1) % n;
var el = elements.eq(newIndex);
var focusElement = el.attr('id');
if ($(this).val() != $(this).data('initial')) {
$('#captured').val(focusElement);
} else if ((currentIndex==0 && event.shiftKey) || (currentIndex==n-1 && !event.shiftKey)) {
event.preventDefault();
if (el.attr('type')=='text') {
$.browser.msie ? "" : $(window).scrollTop(5000);
el.select().delay(800);
} else {
$.browser.msie ? "" : $(window).scrollTop(-5000);
el.focus().delay(800);
}
} else if (el.is('select')) {
event.preventDefault();
if (el.attr('type')=='text') {
el.select();
} else {
el.focus();
}
}
}
});
});
});
});
function setFocus() {
with (document.calculator)
var recap = document.getElementById(recaptured.value);
if (recap!=null) {
setTimeout(function() {
if (recap.getAttribute('type')=='text') {
recap.select();
} else {
recap.focus();
}
}, 1 );
}
}
I put my files available to download in my live link: http://www.presspound.org/calculator/ajax/sample.php

Categories

Resources