Insert text at caret position on textarea

Hi all,

i’m using this to insert text at caret position

textArea.getElement().executeJs("this.shadowRoot.querySelector('[part=\"value\"]').setRangeText($0, -1, -1, \"end\");",
                         "text value");

It runs properly, the only thing is that when i insert the text, it is not synchronized on the server.

How can i make it synchronize


You could return the updated value of the text area in the Javascript expression, and then use the PendingJavaScriptResult returned from executeJs to get the value on the server and set it on the TextArea instance.

Check this Gist here, which has a bunch of ideas for caret positioning etc. with TextArea Vaadin 14/23 TextArea component augmented with cursor and selection API · GitHub

And then the actual solution you want to use.

  1. Add viritin:

(available in Maven central, 1.x version for V23)

  1. Use VTextArea, e.g. like this:
VTextArea ta = new VTextArea();

ta.setValue("Jorma was here");
ta.setSelectionRange(0, "Jorma".length());

ta.addKeyDownListener(Key.F1, e -> {
    ta.getSelectionRange((start, end, text) -> {"Selection is currently %s %s  text: %s ".formatted(start, end, text));