If you are just trying to have placeholder text that gets replaced when a user selects the element then it is obviously best practice to use placeholder
attribute nowadays. However, if you want to select all of the current value when a field gains focus then a combination of @Cory House and @Toastrackenigma answers seems to be most canonical. Use focus
and focusout
events, with handlers that set/release the current focus element, and select all when focused. An angular2/typescript example is as follows (but would be trivial to convert to vanilla js):
Template:
<input type="text" (focus)="focus()" (focusout)="focusout()" ... >
Component:
private focused = false;
public focusout = (): void => {
this.focused = false;
};
public focus = (): void => {
if(this.focused) return;
this.focused = true;
// Timeout for cross browser compatibility (Chrome)
setTimeout(() => { document.execCommand('selectall', null, false); });
};