I want my text boxes have the feature that every time users press enter, it will focus to next closest element whatsoever they are(input, checkbox, button, radio, select, a, div) as long as they can be focused. How can I do that using jquery?
-
1What have you tried? BTW, define `closest` please. Ohhh, another thing, teach the users and maybe yourself as well to use the TAB key. – gdoron Jan 02 '13 at 16:50
-
2Browsers already do that on TAB press. Enter also has a different meaning... why would you want to subvert it? – Ilia G Jan 02 '13 at 16:52
-
next closest is a control you want to input next, not the previous one – sadcat Jan 02 '13 at 16:52
-
2**Don't do this**. That's what the tab key is for. Tab works everywhere and is implemented at the browser level. It is an *extremely* bad idea to try and duplicate this functionality in JavaScript; it means your site will behave wrongly. Every other website on the Internet sets up an expectation for the Enter key to behave a certain way, and your website will break that expectation. – user229044 Jan 02 '13 at 16:54
-
I know we can do this by pressing Tab, but my user want to press enter, the textbox will choose the best suitable item in autocomplete dropdown and focus the next element. – sadcat Jan 02 '13 at 16:57
-
8This is a legitimate technical question and could very well be a business requirement. I have been asked to build such behavior into back office apps quite offten. There are many native apps that behave this way. – Bryan Allo Jan 02 '13 at 16:58
-
@meagar: textbox is for simple, think about other situations need that feature. Have you ever try an accounting software? – sadcat Jan 02 '13 at 16:58
-
@sadcat Yes, I have, and I use tab to navigate between fields. – user229044 Jan 02 '13 at 17:03
-
In my opinion this is bad user expericence and potentially never used. Why? Users have learned that pressing enter in a form might send that form. Thus they're avoiding it to do so. So, your feature might never be used. But +1 for the technical challenge. ;) – try-catch-finally Jan 02 '13 at 19:28
-
This could have been relevant for accessibility. The real question is about navigating to the next focusable element in the tab order. With most accessibility related behavior on this, it isn't generalized like this question intended. A valid solution for something like this is ideal, but you really have to handle loads of other issues, like multiple tabIndexes that are the same on the page, confusing the ordering. Long story short, you're re-implementing a part of the browsers behavior, and it's more complex than it appears and you need to really weight the pros/cons of even attempting. – Scott Jul 17 '14 at 15:58
-
1Maybe you should catch Enter, discard it, and then generate Tab event. – manuell Apr 20 '16 at 14:10
3 Answers
I've already done that before. Try my solution here http://jsfiddle.net/R8PhF/3/
$(document).ready(function(){
$('#mytextbox').keyup(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
var tabables = $("*[tabindex != '-1']:visible");
var index = tabables.index(this);
tabables.eq(index + 1).focus();
}
});
});

- 7,782
- 2
- 24
- 31
-
Thanks for the constructive feedback and understanding the question. +1 – Bryan Allo Jan 02 '13 at 17:08
-
That doesn't handle custom tab indexes, I don't think. So it might work for a certain use case, but not all of them. – Scott Jul 17 '14 at 15:30
-
That's also an invalid selector for focusable. It needs to exclude tabIndex=-1, limit it to the proper elements and constraints and include anything with tabIndex=0 (like divs that aren't traditionally focusable). This isn't exactly what you want, but it's a better start. The selector is the only thing that needs to be changed to get it to work. There is also a jquery ui selector for ':focusable' that could be used. (Fiddle shows brokenness, update filter to get it to work.) http://jsfiddle.net/b45rw/ – Scott Jul 17 '14 at 15:43
By the way, this is a legitimate technical question and could very well be a business requirement. I have been asked to build such behavior into back office apps quite offten. There are many native apps that behave this way.
I addressed this requirement by building my form using DIVs with contenteditable=true like the example below.
<html>
<head>
<style type="text/css">
div.input { border:1px solid #aaa; width:300px; }
</style>
</head>
<body>
<div contenteditable="true" class="input"><strong>explore the world,</strong> e.g. paris, france</div>
</body>
</html>
You can the capture the key event for ENTER and simply set focus on the next sibling using JQuery.
Let me know if you need further clarification.
Hope this helps. Good Luck.

- 696
- 3
- 9
Algorithm-wise:
Keep a list of all elements that can be focussed. Do not rely on the DOM for this. You must keep the list yourself. If you don't know which elements are on the page you've already done something wrong. The DOM is a view not a datastore, treat it accordingly. Many novices who use jQuery make this mistake, and with jQuery this mistake is easy to make.
Find the position of all focussable elements on the page. In accordance with 1. the best way is of course to know the relative position of all elements even without looking at the DOM. With jQuery you can use
.dimension()
. You may have to do some bookkeeping to keep this list up to date (ie. when your data/view changes).Find the position of the current focussed element.
Use some algorithm to compare it to your list of other positions and get the closest (this can mean a lot of things, you probably know what you want).
Then set the focus to the element.
There are many choices you can make here, some depend on performance others depend on interaction and interface design.

- 57,230
- 10
- 89
- 128
-
1
-
1-1 for suggesting that using the DOM API as a Application Programming Interface for a Model that describes the Document as an Object is somehow an anti-pattern. The browser behaviour the OP is looking to determine is something that the browser itself infers using the DOM. Not only is it completely reasonable for the author to try and use the same logic, to do this by trial and error and human observation and maintenance is basically the anti-programming approach. – Barney Aug 24 '15 at 17:19
-
@Barney that's not what I'm suggesting. I posted this a long time ago so I don't know my exact thoughts were. Statements like `$("*[tabindex != '-1']:visible");` query the DOM and try to derive which element is _next_. But, when you're rendering the input elements you already know what order you're rendering them in so you don't need to query the DOM. So long as the logic is simple the _jQuery_ approach works but as soon as you introduce a little bit of complexity (ex: skip a field, skip buttons, last field should submit) you're going to end up with weird code. – Halcyon Aug 25 '15 at 12:33