83

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 :(

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ross
  • 3,709
  • 8
  • 35
  • 33

23 Answers23

99

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

Anjana Silva
  • 8,353
  • 4
  • 51
  • 54
tcdona
  • 1,116
  • 9
  • 8
30

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.

Vitaly Kuznetsov
  • 1,515
  • 1
  • 16
  • 15
  • 4
    I believe this should be the correct answer. The OP did not ask for jquery, and this is far simpler and more compatible. –  Jul 24 '19 at 18:57
  • 2
    Not sure why so many of these answers assume a form is present... This does not work: `Uncaught TypeError: Array.prototype.indexOf called on null or undefined` – Justin Feb 05 '20 at 16:10
  • how do i use this code but only work with textbox not all inputs? – webs Oct 27 '21 at 05:01
  • I used charCode instead of keyCode – Matthias Oct 05 '22 at 05:48
18

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.

Community
  • 1
  • 1
6ft Dan
  • 2,365
  • 1
  • 33
  • 46
  • 4
    What is the purpose of the last bit: `if (e.shiftKey) { enterKey() } else { enterKey() }`? Seems like it should just be: `enterKey()`. – AVProgrammer Mar 28 '16 at 16:43
  • 2
    @AVProgrammer To have *enter* act like *tab* it needs to go in reverse if the *shift* key is held. The line you asked about allows the *enter* key to be checked for while the *shift* key is depressed. – 6ft Dan Mar 29 '16 at 20:23
  • 2
    it doesn't make sense to check for e.shiftKey and call enterKey in both cases. – Jeppe Andreasen Aug 25 '17 at 06:48
  • @JeppeAndreasen If you want it to behave like tab then yes it does. Because Shift+Tab goes in the reverse direction. – 6ft Dan Aug 25 '17 at 11:47
  • 2
    Youre performing the same action regardless if shift is pressed or not. So the if statement is not necessary, as avprogrammer has also pointed out – Jeppe Andreasen Aug 27 '17 at 11:00
  • AVProgrammer was asking, not stating. I've tested the code in my own browser and without the if statement it won't work when shift is held down. – 6ft Dan Aug 28 '17 at 07:17
  • While this code might "work" for you, please take note that it is not correctly written, and as such, if you attempt to amend it in anyway, you are going to face problems. For ONE: `$.inArray(self, focusable)` returns the INDEX of the found element within the array, and -1 if it is not found. Thus, `If ($.inArray(self, focusable))` will not function the way you expect, and will generally always pass. In fact, it does always pass because you cannot compare these jquery objects in this manner, and thus it always returns -1 ! – LittleTreeX Nov 23 '20 at 16:59
  • I have used your example there is a one issue for select2 field it reset the focus to first field. Any idea how to fix it? – Ali Ahmad Pasa Feb 15 '21 at 14:09
12

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;
}
});
Andre Van Zuydam
  • 651
  • 7
  • 12
  • I gave an upvote because I like the code. Although in testing it hasn't worked for me. So I've written a working answer: http://stackoverflow.com/a/27545387/1500195 – 6ft Dan Dec 18 '14 at 11:33
  • `e.keyCode` and `e.which` are deprecated. You should use `e.key === "Enter"`. see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode – oriadam May 06 '19 at 09:13
10

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();
    }

});
isherwood
  • 58,414
  • 16
  • 114
  • 157
Mayur Sarang
  • 157
  • 1
  • 8
4

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>
Damien Sawyer
  • 5,323
  • 3
  • 44
  • 56
  • Your solution is exactly what I was looking for, with one exception: I don't want this behavior on input of type buttons. How can I exclude them? I managed to define the button as – bzamfir Jan 06 '14 at 21:14
  • 1
    Hi. Perhaps try changing the selector as follows? .... $(element).on('keydown', 'input:not(input[type=button]), select', function (e) {..... – Damien Sawyer Jan 07 '14 at 00:40
  • +1; This is great, I use knockout quite a bit, but the project that I need this functionality for is an AngularJS app. If you don't mind, I'll borrow your impl code and post an answer with a custom directive for Angular. – joshperry Jan 08 '14 at 19:13
  • All sweet. Custom bindings are awesome when you get your head around them. :-) – Damien Sawyer Jan 08 '14 at 23:19
4

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.

Andrew
  • 2,094
  • 19
  • 24
  • 1
    Short and concise! Started off with something similar as well, but now I've expanded on it - see my answer (on this page) with [PlusAsTab](http://joelpurra.github.com/plusastab). – Joel Purra Feb 17 '12 at 12:21
  • Was specifically looking for something to steal that considered invisible fields. Most other solutions I found don't. Thanks – Simon_Weaver Sep 24 '16 at 22:21
2

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>
joshperry
  • 41,167
  • 16
  • 88
  • 103
1

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.

Ian Oxley
  • 10,916
  • 6
  • 42
  • 49
  • 2
    Normally I would agree, but our app lets users set stuff like this separately for their own accounts, and the client is offering money for it, so I don't think we can justify holding our ground. – Ross Jun 18 '09 at 14:21
  • Except the default behavior of the enter key is already inconsistent. It only submits if you're within a text input type, most other input types have their own defined behavior for the enter key. As long as he's not mapping the tab key to something else, this seems like a far better solution than the bizarre behavior out of the box. – Beep beep Nov 10 '11 at 11:27
  • 3
    I've found that pressing enter for submit is NOT expected and in fact is highly annoying. In fact in every single website I've ever built the client has asked me to change this behavior as it is unwanted. I blame someone [cough]Microsoft[/cough] that can't admit they made a bad choice for this continued behavior in the face of overwhelming evidence that it's not wanted. –  Nov 12 '14 at 15:10
1

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();
});
Lucio Pelinson
  • 430
  • 5
  • 7
1

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>
oezkanbu
  • 11
  • 1
1
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();
        }
    });
}
pedromaria
  • 19
  • 1
1

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.

Joel Purra
  • 24,294
  • 8
  • 60
  • 60
  • This is interesting. But I have a question: what happens if after page load there are some more UI elements added (like when using knockout binding with an observable array)? What needs to be done to have newly added controls handle Enter as Tab as well? Thanks – bzamfir Jan 06 '14 at 20:39
  • @bzamfir: if it's inside a containing element with `data-plus-as-tab="true"`, you don't need to do anything, otherwise you can run `$("#new-input").plusAsTab()`. Check out [Dynamic elements](https://github.com/joelpurra/plusastab#dynamic-elements) and a sample implementation in this [Improving user experience in HTML forms demo](http://joelpurra.github.io/html-forms/demo-steps/01.html). – Joel Purra Jan 06 '14 at 22:55
0

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.

Jroonk
  • 1,376
  • 1
  • 9
  • 12
0

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

0

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()
    }
  }
jiv-e
  • 483
  • 6
  • 8
0

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

Pat
  • 132
  • 1
  • 10
oriadam
  • 7,747
  • 2
  • 50
  • 48
0

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
}
}
  • Welcome to Stack Overflow. At present, there are 19 other answers to this question. If you are expecting to garner upvotes for yours, please consider explaining why it's better than the rest. – chb May 10 '19 at 22:49
-1

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>  
Bobby Ortiz
  • 3,077
  • 7
  • 35
  • 45
-1

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;
    }
});
-1
$("#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();
    }
});
barbsan
  • 3,418
  • 11
  • 21
  • 28
  • Could you please provide with a small explanation of the code to make the answer more understandably ? – Carles Jun 27 '19 at 06:50
  • firstly you need to select all input fields in form and then you need to bind keypress event in every input fields , then you need to check whether enter keypress or not and when enter key is press in an input field you need to get index of this input field and add increment to index of it to find next input field and when you find next input field you need to focus on it....! – user11706828 Jun 28 '19 at 06:03
-1

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;
        }

    });

}, []);
Reza Rahgozar
  • 99
  • 1
  • 7
-2

You could programatically iterate the form elements adding the onkeydown handler as you go. This way you can reuse the code.

Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168