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.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();
    }
  }

Markup

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>

4 comments:

  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?

    ReplyDelete
  2. Pretty sweet. But, what is with the second part of the if else statement '(input.createTextRange)'? where/how does this get used and what does it do?

    ReplyDelete
  3. but it does not work in mhy case

    ReplyDelete

Blogroll

Popular Posts