5

I found most of what I needed as a solution here:

Add a string of text into an input field when user clicks a button

The problem was I need the text to add in a textarea box at the cursor location - the solution on this page adds the text string to the end of the content of the text area box.

This is my HTML:

<textarea style="width:500px; height: 150px;" id="text">This is some text</textarea>


Here is my Javascript:

$(function () {
$('#button').on('click', function () {
    var text = $('#text');
    text.val(text.val() + "\n\nafter clicking");    
});
$('#button2').on('click', function () {
    var text = $('#text');
    text.val(text.val() + "\n\nafter clicking 2");    
});  });

Here is my JS fiddle with everything working up to this point:

https://jsfiddle.net/2m8L3y3n/

I basically want the inserted text to not just be at the bottom, but wherever the cursor happens to be in the textarea box ...

Also, if I have more than one textarea box on a page, how do I get the buttons to bind to a specific textarea box? On my JS fiddle, I have 2 boxes but only the first one works - is there a way to do this so that I do not have to have a new javascript code for each box? I may have like 10 text area boxes on a page, each with it's own set of buttons, so I am trying to keep the code manageable.

Any help is completely appreciated!

4 Answers 4

3

I've written up an example function of how to accomplish this.

https://jsfiddle.net/axcufrd0/2/

function insertText(text)
{
    var $textbox = $("#text");
    var textStr  = $textbox.text();
    var startPos = $textbox[0].selectionStart;
    var endPos   = $textbox[0].selectionEnd;

    // If set to true, the selection will NOT be replaced.
    // Instead, the text will be inserted before the first highlighted character.
    if (false)
    {
        endPost = startPos;
    }

    var beforeStr = textStr.substr(0, startPos);
    var afterStr  = textStr.substr(endPos, textStr.length);

    textStr = beforeStr + text + afterStr;
    $textbox.text(textStr);
    return textStr;
}

With this, we want to split the text up and then concatenate it with the new content. Depending on how you're doing this, you will either want to replace selection text or append directly before or after.

The one caveat with this code that I have not taken the time to iron out, is that by default the selection text is 0 to 0. This means that no selection appends the text to the very front of the textbox.

2
  • Thank you! That worked like a charm as far as the cursor placement goes - any thoughts on how I can apply that to multiple textboxes on the same page all with it's own set of buttons? May 4, 2016 at 4:54
  • Yes. Review the jQuery documentation on binding events with variables. You can very easily use simple binds to recycle one function. api.jquery.com/on
    – Josh
    May 4, 2016 at 4:57
1

You'll need to get the cursor location (index) and use substring to split the textarea text and concat the strings together for the new text:

See this answer for details on getting the cursor location.

$(function () {
  $.fn.getCursorPosition = function() {
    var el = $(this).get(0);
    var pos = 0;
    if('selectionStart' in el) {
      pos = el.selectionStart;
    } else if('selection' in document) {
      el.focus();
      var Sel = document.selection.createRange();
      var SelLength = document.selection.createRange().text.length;
      Sel.moveStart('character', -el.value.length);
      pos = Sel.text.length - SelLength;
    }
    return pos;
  };

  $('#button').on('click', function () {
    var text = $('#text');
    var cursorLocation = text.getCursorPosition();
    var originalText = text.val();
    var newText = originalText.substring(0, cursorLocation) + 'after clicking' + originalText.substring(cursorLocation);
    text.val(newText);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea style="width:500px; height: 150px;" id="text">This is some text</textarea>
<button id="button">Click Me</button>

0

You can try this.----------------

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

        var front = (txtarea.value).substring(0, strPos);
        var back = (txtarea.value).substring(strPos, txtarea.value.length);
        txtarea.value = front + text + back;
        strPos = strPos + text.length;
        if (br == "ie") {
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart('character', -txtarea.value.length);
            range.moveStart('character', strPos);
            range.moveEnd('character', 0);
            range.select();
        }
        else if (br == "ff") {
            txtarea.selectionStart = strPos;
            txtarea.selectionEnd = strPos;
            txtarea.focus();
        }
        txtarea.scrollTop = scrollPos;
    }
<textarea style="width:500px; height: 150px;" id="text"></textarea>
    <br />
    <input type="button" onclick="insertAtCaret('text', ' text to insert')" value="Click Me to add Text" id="button" />
    <input type="button" onclick="insertAtCaret('text', ' Hello Man')" value="Click Me to add Text" id="button" />

0

References

Code: Function to get current position of cursor

function getCaret(el) {
  if (el.selectionStart) {
    return el.selectionStart;
  } else if (document.selection) {
    el.focus();
    var r = document.selection.createRange();
    if (r == null) {
      return 0;
    }
    var re = el.createTextRange(),
      rc = re.duplicate();
    re.moveToBookmark(r.getBookmark());
    rc.setEndPoint('EndToStart', re);
    return rc.text.length;
  }
  return 0;
}

Button 2 on click:

$('#button2').on('click', function() {
  var text = document.getElementById('text');
  var position = getCaret(text);
  console.log(position);
  console.log(text);
  //text.val(text.val() + "\n\nafter clicking 2");
  var currentPos = getCaret(text);
  //alert(currentPos);
  var strLeft = text.value.substring(0, currentPos);
  var strMiddle = "String to add";
  var strRight = text.value.substring(currentPos, text.value.length);
  text.value = strLeft + strMiddle + strRight;
});

Let me know if anything is not clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.