1

I am looking to make the enter key behave exactly like the tab key on a form.

I am stuck on the fireEvent section.

var inputs = $$('input, textarea');
    $each(inputs,function(el,i) {
    el.addEvent('keypress',function(e) {
    if(e.key == 'enter') {
        e.stop();
        el.fireEvent('keypress','tab');
    }
    });
});

How do I fire a keypress event with a specified key? Any help would be greatly appreciated.

Adriaan Nel
  • 370
  • 1
  • 11

2 Answers2

1

this will work but it relies on dom order and not tabindex

var inputs = $$('input,textarea');

inputs.each(function(el,i){
    el.addEvent('keypress',function(e) {
        if(e.key == 'enter'){
            e.stop();
            var next = inputs[i+1];
            if (next){ 
                next.focus();
            }
            else {
                // inputs[0].focus(); or form.submit() etc.
            }
        }
    });
});

additionally, textarea enter capture? why, it's multiline... anyway, to do it at keyboard level, look at Syn. https://github.com/bitovi/syn

the above will fail with hidden elements (you can filter) and disabled elements etc. you get the idea, though - focus(). not sure what it will do on input[type=radio|checkbox|range] etc.

p.s. your code won't work because .fireEvent() will only call the bound event handler, not actually create the event for you.

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69
  • Thanks, I tried this code, but the problem here is that the $$() array doesn't necessarily return elements in order, as textareas will follow after inputs. Further more, if new items are added dynamically, the array would need to be refreshed. – Adriaan Nel Jul 08 '13 at 21:25
  • then you need to consider keeping tabindexes correctly and `this.getNext('input[tabindex=' + this.get('tabindex'))` - or fire the key event manually cross browser - which is no small task. – Dimitar Christoff Jul 08 '13 at 21:46
  • I decided to add a specific class to the specific inputs and textareas, which caused them to be returned in the correct order. – Adriaan Nel Jul 09 '13 at 05:48
0

Take a look at the class keyboard (MooTools More).

It can fire individual events for keys and provides methodology to disable and enable the listeners assigned to a Keyboard instance.

The manual has some examples how to work with this class, here's just a simple example how I implemented it in a similar situation:

var myKeyEv1 = new Keyboard({
    defaultEventType: 'keydown'
});

myKeyEv1.addEvents({
    'shift+h': myApp.help()   // <- calls a function opening a help screen
});

Regarding the enter key in your example, you have to return false somewhere to prevent the enter-event from firing. Check out this SO post for more details.

Community
  • 1
  • 1
Bjoern
  • 15,934
  • 4
  • 43
  • 48