Insert character at last cursor position inside input

Asked

Viewed 451 times

3

I have the following code:

$('#mais').click(function(){
  $('#console').val($('#console').val() +"+");
});

$('#menos').click(function(){
  $('#console').val($('#console').val() +"-");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="console" type="text">
<button id="mais">+</button>
<button id="menos">-</button>

In this code I can insert the characters at the end of the input whenever I click on the corresponding buttons, but how do I insert in the last position of the text cursor inside the input?

Example:

  1. I typed the text:
  2. maismais
  3. I placed the text cursor in the middle of the text:
  4. mais|mais
  5. I clicked the button -, I would like the result to be this:
  6. mais-mais

3 answers

2

Hello!

That’s how it worked!

var element = $('#console');

$('#mais').click(function(){
	addChar('+', element);
});

$('#menos').click(function(){
	addChar('-', element);
});
 
function addChar(c, el) {
  var text = el.val();
  var pos = el[0].selectionStart;		// posição do cursor
  
  // insere o caracter
  el.val(text.substring(0, pos) + c + text.substring(pos));
  
  // voltar para o input
  el.focus();
  
  // posicionar o cursor na ultima posição
  el[0].selectionStart = pos + 1;
  el[0].selectionEnd = pos + 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="console" type="text">
<button id="mais">+</button>
<button id="menos">-</button>

Adapted from https://stackoverflow.com/a/15977052/5789135

  • While this link may answer the question, it is best to include the essential parts of the answer here and provide the link for reference. Replies per link only can be invalidated if the page with the link is changed. - Of Revision

  • I edited the answer.

  • To get better I’d have to explain your answer ?

2


This script does what it proposes. It inserts the click button signal and keeps the cursor focused on the field.

I suggest to simplify the code: instead of using two functions for each button, use only one:

$('#mais, #menos').click(function(e){
   insereSinal('#console', e.target.textContent);
});

$('#mais, #menos').click(function(e){
   insereSinal('#console', e.target.textContent);
});

function insereSinal(cId, sinal){
   var cam = $(cId)[0];
   var cvl = $(cam).val();
   var cps = cam.selectionStart;
   var ini = cvl.substring(0, cps);
   var fim = cvl.substring(cps, cvl.length);
   $(cam).val(ini+sinal+fim);
   cps += sinal.length;
   cam.selectionStart = cam.selectionEnd = cps;
   cam.focus();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="console" type="text">
<button id="mais">+</button>
<button id="menos">-</button>

If you want the function compressed:

$('#mais,#menos').click(function(e){insereSinal('#console',e.target.textContent);});
function insereSinal(cId,sinal){var cam=$(cId)[0];var cvl=$(cam).val();
var cps=cam.selectionStart;var ini=cvl.substring(0,cps);
var fim=cvl.substring(cps,cvl.length);$(cam).val(ini+sinal+fim);
cps+=sinal.length;cam.selectionStart=cam.selectionEnd=cps;cam.focus();}

Compatibility: IE9+, Edge, FF, Chrome, Safari, Opera

Source: Soen (with adaptations and considerable code reduction)

1

This javascript function will allow you to easily insert text into an input where the cursor is.

In this case the sign + or - on the onclick of the buttons

onclick="inserirSinal('console', '-') 

or

onclick="inserirSinal('console', '+')

function inserirSinal(inputId, text) {
  var input = document.getElementById(inputId);
  if (!input) { return; }
  var scrollPos = input.scrollTop;
  var strPos = 0;
  var br = ((input.selectionStart || input.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
  if (br == "ie") {
    input.focus();
    var range = document.selection.createRange();
    range.moveStart ('character', -input.value.length);
    strPos = range.text.length;
  } else if (br == "ff") {
    strPos = input.selectionStart;
  }

  var front = (input.value).substring(0, strPos);
  var back = (input.value).substring(strPos, input.value.length);
  input.value = front + text + back;
  strPos = strPos + text.length;
  if (br == "ie") {
    input.focus();
    var ieRange = document.selection.createRange();
    ieRange.moveStart ('character', -input.value.length);
    ieRange.moveStart ('character', strPos);
    ieRange.moveEnd ('character', 0);
    ieRange.select();
  } else if (br == "ff") {
    input.selectionStart = strPos;
    input.selectionEnd = strPos;
    input.focus();
  }

  input.scrollTop = scrollPos;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="console" type="text" value="maismais">
<button id="mais" onclick="inserirSinal('console', '-');return false;">-</a>
<button id="menos" onclick="inserirSinal('console', '+');return false;">+</a>

Firefox, IE7, Opera, Safari and Chrome.

Credits

Browser other questions tagged

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