/ Published in: JavaScript
This code makes Enter key get the behavior of the Tab Key for forms.
The shift event on the above function to go back between elements.
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.
The shift event on the above function to go back between elements.
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// 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() } });
URL: http://stackoverflow.com/questions/1009808/enter-key-press-behaves-like-a-tab-in-javascript