I have an input text, I need to click a button to add a specific word in the place where the cursor is positioned, that is, I have to get the cursor position in the input and add a word there.
Can anyone help me?
I have an input text, I need to click a button to add a specific word in the place where the cursor is positioned, that is, I have to get the cursor position in the input and add a word there.
Can anyone help me?
Here's a suggestion:
It saves the position of the cursor during the keyup
and so you know where the last position was.
var input = document.querySelector('input');
var caret = 0;
var texto = '_olá!_';
input.addEventListener('keyup', function() {
caret = this.selectionStart;
});
var button = document.querySelector('button');
button.addEventListener('click', function() {
var val = input.value;
input.value = val.slice(0, caret) + texto + val.slice(caret);
});