CKTIS / HTML
onselect — handling text selection
The onselect attribute defines JavaScript that runs when a select event occurs, typically when text is selected in an input or textarea control. It does not detect option selection in a select element.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
onselect="JavaScript statements"
element.onselect = function (event) { /* handler */ }onselect is an event handler content attribute for the select event. It is available on all HTML elements, but adding it does not make an element generate such events. Its typical use is responding to text selection in supporting input controls and in textarea; selection can also be changed programmatically.
The attribute value is JavaScript code, not a Boolean value or merely a function name. Inside an inline handler, event represents the event and this refers to the element handling it. Read selection boundaries through selectionStart and selectionEnd; the second index is excluded from the selected substring.
The corresponding JavaScript property, element.onselect, accepts a function; assigning another replaces the previous handler in that slot. An alternative is addEventListener('select', handler). Do not confuse the select event with the select element: use input or change to respond to a change of selected option.
The example sets the range from index 1 to 5 in Hello. After the event is handled, the result is Selected: ello. JavaScript and inline event handlers must be enabled; a Content Security Policy can block inline handlers.
Examples
<!doctype html>
<meta charset="utf-8">
<title>onselect demo</title>
<label>Text: <input id="text" type="text" value="Hello" onselect="document.getElementById('result').textContent = this.value.slice(this.selectionStart, this.selectionEnd)"></label>
<p>Selected: <output id="result"></output></p>
<script>
document.getElementById('text').setSelectionRange(1, 5);
</script>Result
Selected: ello
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.