Add text at a given input text position

Asked

Viewed 607 times

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, I mean, I have to take the position of the cursor in the input and add a word.

Someone can help me?

  • 2

    "I need you to click a button" - This makes things a little difficult because clicking outside the input makes it lose focus and the cursor is no longer there... You can explain what you want to do better?

  • Whoa, that’s good thinking. During input completion it will be necessary to add a certain word that later that place with the word will be replaced by other values. In this case, clicking the button will be the fastest way to add such a word.

1 answer

2


Here’s a suggestion:

Saves cursor position during 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: https://jsfiddle.net/wc2khavd/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.