How to select all text of input at page load in Chrome/Firefox in combination with autofocus

1.1k views Asked by At

My question is: How can I convince also Chrome/Opera and Firefox that a specific input is focused when/after the page is loaded (by using autofocus) AND also its text is selected by default.

The closest answers to my use case are about how to select the text of an input when the element gets focus by clicking on it.

The most appropriate answer (imho) to my question would be:

// file: scripts.js

function onFocusSelectAll(sender) {
  // setTimeout(function () { ... }, 0) is required for edge and safari
  setTimeout(function() {
    sender.select();
  }, 0);
}
<input id="searchInput" type="text" onfocus="onFocusSelectAll(this);">

Taken and modified from this SO answer

But that's just half the truth. Although this works in many browsers (edge, IE, Safari) no text will be selected in Chrome/Opera or Firefox

1

There are 1 answers

0
markus s On BEST ANSWER

After playing around I found out that my solution was actually correct...

// file: scripts.js

function onFocusSelectAll(sender) {
  // setTimeout(function () { ... }, 0) is required for edge and safari
  setTimeout(function() {
    sender.select();
  }, 0);
}

...But that browsers execute the initial focus event at different times.

Chrome/Opera and Firefox execute the focus event triggered by autofocus before the external scripts are loaded when added at the end of the page synchronously.

So make sure your relevant scripts are either loaded above their usage or you use inpage/inline scripts for that specific purpose.

Edit: An alternative would be to handle the autofocus yourself and not use this property at all.

(function setInitialFocus() {
  elem = document.getElementById("searchInput");
  elem.select();
})();
<input id="searchInput" type="text" onfocus="onFocusSelectAll(this);">