Insert character at last cursor position within input

2

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><inputid="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 input ?

Example:

  • I typed the text:
  •     
    maismais
  • I placed the text cursor in the middle of the text:
  •     
    mais|mais
  • I clicked the - button, I would like the result to be this:
  •     
    mais-mais
    asked by anonymous 22.11.2017 / 00:38

    3 answers

    1

    This script does what it proposes. It inserts the clicked 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><inputid="console" type="text">
    <button id="mais">+</button>
    <button id="menos">-</button>

    If you want the compressed function:

    $('#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)

        
    22.11.2017 / 01:35
    1

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

    In this case, the + or - sign 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><inputid="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

        
    22.11.2017 / 01:43
    1

    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><inputid="console" type="text">
    <button id="mais">+</button>
    <button id="menos">-</button>

    Adapted from link

        
    22.11.2017 / 01:08