Search code examples
javascriptpositioncaret

Change caret position in textarea by click on button


I have a textarea with this content :

[supreme] a test text or anything [/supreme]

I have a button too. I want to when button clicked , textarea selected and change caret position to this :

[supreme] a test text or anything  <caret postion> [/supreme]

How can i do this with javascript or jquery ?

Thanks .


Solution

  • Here is a quick example. It could be done cleaner but it should get you started.

    $(document).ready(function() {
      $('.button').click(function(e) {
        var $textArea = $('.textArea');
        var prevValue = $textArea.val();
        $textArea.focus().val('').val(prevValue);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea class="textArea">a test text or anything</textarea>
    <button class="button">
    CLick Me
    </button>