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.

1
  • 1
    so far it seems this is not possible...I'd love to be proved wrong :) Commented Jul 6, 2013 at 8:53

2 Answers 2

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.

3
  • 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. Commented Jul 8, 2013 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. Commented Jul 8, 2013 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. Commented Jul 9, 2013 at 5: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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.