Add text in a certain position of the input text

1

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?

    
asked by anonymous 02.08.2016 / 19:04

1 answer

2

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);
});

jsFiddle: link

    
02.08.2016 / 19:20