When can the setSelectionRange method of Htmlinputelement be used?

Asked

Viewed 434 times

1

Studying the structure of an element HTMLInputElement I arrived at the method setSelectionRange, selecting the text from the positions defined by the parameters, i.e. input.setSelectionRange(0, 8) will select the characters between positions 0 and 8 of the element value input. However, I saw a behavior that, at first, seemed strange and I have not found 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 content of the field should be selected between positions 0 and 8, in the case "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 it is possible to verify, the content is correctly selected when the field receives the focus, but when pressing 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 message appears on console.

Is this behavior what is expected in this situation? If so, is there any official source to explain why it is so? If not, why not work on some browsers?

1 answer

3


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

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

One way around that is to call the input.focus(); inside the Handler of click.

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>

  • 1

    In fact, that’s it. I’m using this in a custom element with Stencil and calling the method setSelectionRange of the element I want to implement the same input internal. With the focus worked, even if the select had worked without needing to set focus. Thank you.

  • @Andersoncarloswoss great. It would be good to be clearer in the specs of HTML5 or Ecmascript.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.