Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 331
user5302198 Avatar asked May 04 '16 04:05

user5302198


People also ask

How to insert text into the input at the current cursor position?

First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.

How do I add text to textarea?

To add text to a textarea, access the value property on the element and set it to its current value plus the text to be appended, e.g. textarea. value += 'Appended text' . The value property can be used to get and set the content of a textarea element.


2 Answers

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.

like image 150
Josh Avatar answered Oct 23 '22 09:10

Josh


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>
like image 1
Gabriel McAdams Avatar answered Oct 23 '22 10:10

Gabriel McAdams