user5302198
user5302198

Reputation: 61

Add a string of text into an input field when user clicks a button (At Cursor Location)

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!

Upvotes: 5

Views: 4562

Answers (4)

NIKHILESH GUPTA
NIKHILESH GUPTA

Reputation: 26

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.

Upvotes: 0

Mamun
Mamun

Reputation: 145

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" />

Upvotes: 0

Gabriel McAdams
Gabriel McAdams

Reputation: 58251

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>

Upvotes: 1

Josh
Josh

Reputation: 3288

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.

Upvotes: 3

Related Questions