Answer the question
In order to leave comments, you need to log in
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
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>
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;
On Jquery - $("#id_code").focus();
htmlbook.ru/html/textarea/autofocus
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question