Add text at cursor in text area.

Hi all,

i’m using javascript to add a text at caret position into a TextArea.

TextArea textArea = new TextArea();

textArea.getElement().executeJs("this.shadowRoot.querySelector('[part=\"value\"]').setRangeText($0);", " My Text ");


It runs ok, the only problem is that if i do not write nothing after the javascript execution, the data are not sent to server, so the data are not saved.

if i write something into the textArea by hand, so, the data are sent properly to server side.

what i need is to tell TextArea to take the content and send it to server side.

Any hint ?

PS: It will be very useful to have a insertAtCaretPosition() function on TextField and TextArea

If we only would have gotten my PR in, you could do this in pure Java in 23.2 :grimacing: Added selection API to simple input based fields by mstahv · Pull Request #3194 · vaadin/flow-components · GitHub

Without trying anything, did you try different value change mode? For example: setValueChangeMode(ValueChangeMode.LAZY);

I’m getting a JS exception with your code, but you can try a “preview version” of that PR I referred if you use Viritin add-on (Maven coordinates: in.virit:viritin:1.5.0)

    Button b = new Button("D");
    VTextArea viritinTextArea = new VTextArea();
    add(viritinTextArea, b);

    b.addClickListener(e -> {
        viritinTextArea.getCursorPosition(index -> {
            String curStr = viritinTextArea.getValue();
            viritinTextArea.setValue(curStr.substring(0, index) + "foobar" + curStr.substring(index));

Hi Matti, thanks for the suggestions, i’ll try them

BTW. Which version are you using? There was some DOM re-structuring due to the accessibility improvements project. So if you are still on V14, that could have been the issue why your js caused and exception to me. Also the latest Viritin version requires 23.x series.

Hi, at the moment i’m using the last V14, in the next months i’ll plan to migrate to 23.2