0

I have the following code for selecting all text inside input field:

<input id="userName" class="form-control" 
type="text" name="enteredUserName" data-ng-show="vm.userNameDisplayed()" 
    data-ng-model="vm.enteredUserName">

and method to select all text:

vm.userNameDisplayed = function() {
    var textArea = angular.element('#userName');
    textArea.setSelectionRange(0, vm.enteredUserName.length)
}

but after calling this method nothing is selected.

masud_moni
  • 1,121
  • 16
  • 33
Ted
  • 1,682
  • 3
  • 25
  • 52
  • https://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked – Saurabh Agrawal Aug 01 '17 at 08:49
  • 1. I don't need to do it on onClick method 2. I have the same code as in provided example – Ted Aug 01 '17 at 08:51
  • When do you expect the text to be selected? As soon as user types? – Prerak Sola Aug 01 '17 at 08:54
  • Secondly, `ng-show` expects an expression that resolves to truthy/falsy. In your case, the function `userNameDisplayed` will be called when the page is rendered. If there is no data at that time, it will not select anything. – Prerak Sola Aug 01 '17 at 08:56
  • Searching on the title returns [*5,000 results*](https://stackoverflow.com/search?q=%5Bjavascript%5D+select+all+text+in+input). – RobG Aug 01 '17 at 09:14

1 Answers1

1

Try focusing the textArea first using textArea.focus();

vm.userNameDisplayed = function() {
    var textArea = angular.element('#userName');
    textArea.focus();
    textArea.setSelectionRange(0, vm.enteredUserName.length)
}
A Rogue Otaku
  • 913
  • 10
  • 20