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?
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 sameinput
internal. With thefocus
worked, even if theselect
had worked without needing to set focus. Thank you.– Woss
@Andersoncarloswoss great. It would be good to be clearer in the specs of HTML5 or Ecmascript.
– Sergio