We can select content of text field using setSelectionRange function of javascript. To this function we have to pass the starting and ending point. Here we will pass both starting and ending point as cursor location.

Script to select text in input fields

Here we have to pass starting and ending point as cursor location
setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
      input.setSelectionRange(selectionStart, selectionEnd);
    } else if (input.createTextRange) {
      var range = input.createTextRange();
      range.moveEnd('character', selectionEnd);
      range.moveStart('character', selectionStart);


Here we are calling setSelectionRange on button click with starting and ending point as user specified  cursor location
<input #myInput type="number" value="3"/>
<button (click)="setSelectionRange(myTextArea, myInput.value, myInput.value)">Set Caret Position</button>
<textarea rows="4" #myTextArea cols="40">Sample Text Here</textarea>

1 comment:

  1. Any thoughts on making this, combined with your other post about getting the cursor position, into a directive that could be reused on any number of inputs?



Follow this blog by Email

Popular Posts