TextField, change value and ENTER key

Hi guys! I need to do the next. I have a TextField and when the value change I need to call a functionA(). But when the user press the enter key I need first to call functionA() and second functionB(), in that order.

I tried to do:

TextField tf = new TextField();
tf.addValueChangeListener(event → functionA());
tf.addKeyDownListener(Key.ENTER, event → functionB());

but when enter key is press, functionB() is call before functionA()

Someone knows how can I do that?.. Thanks.

How about this:

tf.addKeyDownListener(Key.ENTER, event -> {functionA(); functionB();});

Hi Olli! The problem is that I need functionA() should always be called when a value in TextField change but functionB() should only be called when enter key is press.

If I do this

TextField tf = new TextField();
tf.addValueChangeListener(event → functionA());
tf.addKeyDownListener(Key.ENTER, event → {functionA(); functionB();});

functionA() will be called two times when Enter key is press.

Set a flag and only execute what’s in function A if it’s the first time

I tried to put a flag but the problem is more complicated. I need to use the TextField value for some operations but addKeyDownListener() is called always before addValueChangeListener(). And when addKeyDownListener() is called TextField value hasn’t been set yet because addValueChangeListener hasn’t been called.

Okay, so your problem is actually quite different from what you initially posted. You might want to look at this ticket for some workarounds: Shortcut listener on TextField sees old values · Issue #17484 · vaadin/flow · GitHub

as a sidenote, the value change listener isn’t the one that updates the value, but rather, it reacts to the change event in the browser, which hasn’t occurred yet in the case of the keyboard shortcut.

I’ve a scenario where when user presses ENTER key, he/she wants the focus moved to another component. Say, there are two text fields and one button. When user presses ENTEY key, automatically move foucs from textfield 1 to textfield 2 and then to button.

The user is accoustmoed to use ENTER key and they don’t prefer TAB

How can I automatically move the focus here fron one component to another in a sequence ?

You can call .focus() on the next component