2

I can't believe this hasn't been asked before (I searched and searched) but anyway.

How can I switch key events with pure JS?

For example, I want to switch the Enter button to mimic the Tab button. (I want to be able to push enter without submitting the form and instead switch fields to a Tab-like behavior e.i. switch form fields)

Tek
  • 2,888
  • 5
  • 45
  • 73
  • Frameworks are (generally) pure JavaScript, and they take care of nifty things like different browsers having different ways of representing key presses in events. – Quentin Jan 31 '11 at 22:50
  • That's fine, I only need to make it work on one browser since only one person will be using it. – Tek Jan 31 '11 at 23:08

1 Answers1

2
var enter = 13;
if (e.which === enter) {
    // tabs to next field
    getNextField(e.srcElement).focus();
    // stops default enter
    event.preventDefault();
    event.stopPropagation();
}

implement getNextField() using .tabindex

function getNextField(obj) {
   var next = obj.tabIndex + 1;
   var all = document.getElementsByTagName("*");
   for (var i in all) {
       if (all[i].tabIndex === next) {
           all[i].focus();
           break;
       }

   }
}

This should give you a vague idea of how to do it. Flesh out the pseudocode yourself.

Raynos
  • 166,823
  • 56
  • 351
  • 396