Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter key press behaves like a Tab in 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 :(

like image 422
Ross Avatar asked Jun 17 '09 22:06

Ross


1 Answers

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

like image 119
tcdona Avatar answered Sep 18 '22 21:09

tcdona