Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  117] [ 1]  / answers: 1 / hits: 186104  / 15 Years ago, wed, june 17, 2009, 12:00:00

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


More From » html

 Answers
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


[#99289] Sunday, June 14, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brooksb

Total Points: 480
Total Questions: 98
Total Answers: 106

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
brooksb questions
Tue, Nov 9, 21, 00:00, 3 Years ago
Mon, May 4, 20, 00:00, 4 Years ago
Wed, Mar 11, 20, 00:00, 4 Years ago
;