4

Is there any specific way to add shortcut Listener for the Enter Key on a specific TextField element in Vaadin Flow. The documentation is silent about this.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Aiden
  • 335
  • 2
  • 10

2 Answers2

6

I guess you are not actually looking for a ”shortcut” key but to react to enter presses when the focus is inside the field? If so, see KeyNotifier and e.g. addKeyPressListener.

It is also possible to listen to any DOM event using the element API, e.g.

textField.getElement().addEventListener("keyup", e -> { 
    System.out.println("Value is now: " + 
        e.getEventData().getString("element.value"));
}).addEventData("element.value").setFilter("event.keyCode == 13");
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Artur Signell
  • 1,694
  • 9
  • 9
  • 3
    I'd recommend making the code more readable through filtering by `event.key = 'Enter'` instead of using obscure key codes. – Leif Åstrand May 06 '18 at 19:27
3

In the Vaadin Directory there is a UI Web Component for Vaadin 10. It's called shortcut. The usage is very simple:

Shortcut.add(messageField, Key.ENTER, sendButton::click);

You also can also add modifier keys like that:

Shortcut.add(messageField, Key.ENTER, sendButton::click, Key.SHIFT);
pernpas
  • 199
  • 3
  • 17