The HTMLInputElement.setSelectionRange()
method sets the start and end positions of the current text selection in an <input>
element.
Optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred; this lets you indicate, for example, that the selection as set by the user clicking and dragging from the end of the selected text toward the beginning.
This method updates HTMLInputElement.selectionStart
, selectionEnd
, and selectionDirection
in one call.
inputElement.setSelectionRange(selectionStart, selectionEnd[, selectionDirection]);
The following code:
<!DOCTYPE html> <html> <head> <meta charset=utf-8> <title>JS Bin</title> <script> function SelectText () { var input = document.getElementById("mytextbox"); input.focus(); input.setSelectionRange(2,5); } </script> </head> <body> <p><input type="text" id="mytextbox" size="20" value="Mozilla"/></p> <p><button onclick="SelectText()">Select text</button></p> </body> </html>
will produce the following:
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'HTMLInputElement.setSelectionRange()' in that specification. | Living Standard | No change |
HTML 5.1 The definition of 'HTMLInputElement.setSelectionRange()' in that specification. | Recommendation | No change |
HTML5 The definition of 'HTMLInputElement.setSelectionRange()' in that specification. | Recommendation | Initial definition |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 1 | Yes | 1 | 9 | 8 | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes | ? | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange