When can the setSelectionRange method of HTMLInputElement be used?

2

Studying the structure of an element HTMLInputElement I got to method setSelectionRange , which makes the text selection between the positions defined by the parameters, ie input.setSelectionRange(0, 8) will select the characters between positions 0 and 8 of the value of the input element. However, I saw a behavior that at first seemed strange and I still did not find official sources to explain it.

Consider the example below: a text field and a button; both when the text field receives the focus and the button is pressed, the contents of the field should be selected between positions 0 and 8, in the case of "Anderson".

const input = document.querySelector("input");
const button = document.querySelector("button");

input.addEventListener("focus", function (event) {
  this.setSelectionRange(0, 8);
});

button.addEventListener("click", function (event) {
  input.setSelectionRange(0, 8);
});
<input type="text" value="Anderson Carlos Woss">
<button>Selecionar</button>

As you can see, content is selected correctly when the field receives focus, but when you press the button, nothing happens. This behavior has been verified in both Opera, Firefox and Chrome and, interestingly, works as expected in IE11 and Edge. No messages appear in console .

Is this behavior expected in this situation? If so, is there any official source explaining why this is so? If not, why did not it work in some browsers?

    
asked by anonymous 18.10.2017 / 15:49

1 answer

3

I think this happens because you can only select content in elements that are in focus. Although I did not find this written, it makes sense and in the MDN example is what they do . The closest and most indirect reference I found was this note for the .select method:

  

Running element.select() will not necessarily focus on input , so it is often used in conjunction with HTMLElement.focus() .

One way around this is to call input.focus(); inside the click handler.

const input = document.querySelector("input");
const button = document.querySelector("button");

input.addEventListener("focus", function (event) {
  this.setSelectionRange(0, 8);
});

button.addEventListener("click", () => input.focus());
<input type="text" value="Anderson Carlos Woss">
<button>Selecionar</button>
    
18.10.2017 / 17:08