V
V
vlzkonopatov2015-05-12 16:27:52
JavaScript
vlzkonopatov, 2015-05-12 16:27:52

How to set cursor inside Textarea text?

I have a modal window element and in it:

<textarea name="code" id="id_code" style="width: 100%;" rows="16" data-ng-model="current_static_page_code"></textarea>
I assign a default value to the mind like this:
$scope.current_static_page_code = '<body style="margin: 0; width: 100%; height: 100%;">\n\n</body>';
How can I make the cursor automatically set between \n

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
vlzkonopatov, 2015-05-14
@vlzkonopatov

If anyone needs it, here it is.

$scope.caretPos = 6;

$scope.setSelectionRange = function(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
      input.focus();
      input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
      var range = input.createTextRange();
      range.collapse(true);
      range.moveEnd('character', selectionEnd);
      range.moveStart('character', selectionStart);
      range.select();
    }
};

$scope.setCaretToPos = function() {
     $scope.setSelectionRange(document.getElementById("myTextArea"), $scope.caretPos, $scope.caretPos);
};

Caret Positon :<br/>
<input type="number" ng-model="caretPos"/><br/><br/>
<textarea id="myTextArea">
This is sample text for testing purpose
</textarea><br/><br/>
<button ng-click="setCaretToPos()">Set Caret Position</button>

Demo: demo.sodhanalibrary.com/angular/cursor_position_us...

A
Alexander, 2015-05-12
@NeiroNx

https://developer.mozilla.org/en-US/docs/Web/API/H...
the cursor is set like this if the length is 2 characters.

$("#id_code").selectionStart = 1;
$("#id_code").selectionEnd = 1;

And if you are using a plugin that replaces textarea, then this method will not work. The plugin has its own functions for this.

A
Alex Orlov, 2015-05-12
@firohn

On Jquery - $("#id_code").focus();
htmlbook.ru/html/textarea/autofocus

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question