HTML onselect Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onselect attribute is an inline event handler that runs JavaScript when the select event fires — when the user highlights text inside an <input> or <textarea>. Use it to show selection counts, enable a “format selection” button, validate highlighted content, or provide contextual help. Read the selection with selectionStart, selectionEnd, and value.substring(). For selections anywhere on the page, use document.selectionchange or window.getSelection() instead. Prefer addEventListener("select", …) in production.

What You’ll Learn

01

Event handler

Inline JS.

02

select

Text highlight.

03

input / textarea

Form fields.

04

selectionStart

Read range.

05

vs oncopy

Select vs copy.

06

addEventListener

Preferred way.

Purpose of onselect Attribute

The primary purpose of onselect is to react when the user selects (highlights) text inside a form control — so your page can show how many characters are selected, reveal formatting tools, or run validation on the highlighted portion only.

The select event fires on the element where the selection occurs. It does not fire when the user copies text — use oncopy for clipboard actions — and it does not apply to arbitrary page content outside inputs and textareas.

💡
Highlight only, not copy

onselect runs when text is highlighted. Use oncopy if you need to react when the user actually copies to the clipboard.

📝 Syntax

Set onselect on an <input> or <textarea>, or assign element.onselect in JavaScript:

onselect.html
<input type="text" onselect="handleSelection()">

<textarea onselect="handleSelection()"></textarea>

<script>
  field.onselect = handleSelection;
  field.addEventListener("select", handleSelection);
</script>

Syntax Rules

  • Value is JavaScript executed when the select event fires.
  • Works on text-like <input> types and <textarea>.
  • Fires when the user highlights text with mouse or keyboard.
  • Read selection with selectionStart and selectionEnd.
  • Also assignable as element.onselect in script.
  • Modern alternative: addEventListener("select", handler).
  • For page-wide selection, use document.addEventListener("selectionchange", …).

💎 Values

The onselect attribute accepts a string of JavaScript code:

  • onselect="handleSelection()" — Call a named function.
  • onselect="showCount()" — Display selected character count.
  • JavaScript: input.onselect = () => { … } — property assignment.
onselect-handler.html
function handleSelection() {
  var start = field.selectionStart;
  var end = field.selectionEnd;
  var selected = field.value.substring(start, end);
  count.textContent = selected.length + " characters selected";
}

field.addEventListener("select", handleSelection);

⚡ Quick Reference

Property / APIWhen it runsNotes
selectText highlighted in fieldonselect
selectionStartRead anytimeStart index of selection
selectionEndRead anytimeEnd index of selection
copyUser copies to clipboardoncopy
selectionchangeAny page selectionOn document

Applicable Elements

ElementSupported?Notes
<input type="text">YesPrimary use
<input type="search">, email, urlYesText-like inputs
<textarea>YesMulti-line text
<input type="checkbox">NoNo selectable text value
<p>, <div>NoUse selectionchange on document

onselect vs oncopy vs selectionchange

HandlerWhen it firesTypical use
onselectText highlighted in input/textareaSelection count, format tools
oncopyUser copies (Ctrl+C)Analytics, clipboard modify
selectionchangeAny selection on pageHighlight toolbar on articles
oninputValue changesLive typing — not selection

Examples Gallery

Textarea inline handler, dynamic assignment, and selected character count with addEventListener.

👀 Live Preview

Highlight text below — the selection count updates:

0 characters selected

Example — onselect on textarea

Run a function when the user highlights text:

textarea-onselect.html
<textarea onselect="showSelection()">Select some text here</textarea>
<p id="status"></p>

<script>
  function showSelection() {
    document.getElementById("status").textContent = "Text selected!";
  }
</script>
Try It Yourself

How It Works

When the user selects text inside the textarea, the browser fires select and runs showSelection(). Drag with the mouse or use Shift+arrow keys to highlight text.

Dynamic Values with JavaScript

Assign the handler on an input at runtime:

dynamic-onselect.html
<script>
  document.getElementById("dynamicInput").onselect = function () {
    log.textContent = "Text selected dynamically!";
  };
</script>
Try It Yourself

How It Works

Assigning element.onselect is equivalent to the inline attribute. Use this when you attach the handler after the DOM loads.

Example — Selected character count

Read selectionStart and selectionEnd to show how much text is highlighted:

selection-count.html
field.addEventListener("select", function () {
  var len = this.selectionEnd - this.selectionStart;
  var text = this.value.substring(this.selectionStart, this.selectionEnd);
  count.textContent = len + " chars: \"" + text + "\"";
});
Try It Yourself

How It Works

selectionStart and selectionEnd are zero-based indices into value. Their difference is the number of selected characters.

♿ Accessibility

  • Do not block selection — Never use CSS user-select: none on content users need to copy.
  • Keyboard selection — Support Shift+arrow keys; test that select fires for keyboard users.
  • Announce changes — Use aria-live="polite" when selection count updates.
  • Visible focus — Ensure inputs and textareas have clear focus styles before selection.
  • Respect user intent — Avoid intrusive popups immediately on every text highlight.

🧠 How onselect Works

1

User highlights text

Mouse or keyboard.

Input
2

select fires

onselect runs.

Event
3

Read selection

start / end indices.

API
=

Update UI

Count, tools, validation.

Browser Support

The select event and onselect handler are supported in all modern browsers on input and textarea elements.

UI Events · Fully supported

Universal onselect support

All major browsers fire select when text is highlighted in form fields.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer Fully supported
Full support
Opera Fully supported
Full support
onselect attribute 99% supported

Bottom line: Reliable for text selection handling on form fields in all modern browsers.

💡 Best Practices

✅ Do

  • Use selectionStart / selectionEnd to read highlighted text
  • Use addEventListener("select", …) in production
  • Pair with keyboard-friendly selection (Shift+arrows)
  • Use selectionchange for page-wide highlight toolbars
  • Keep selection feedback subtle and non-blocking

❌ Don’t

  • Confuse onselect with oncopy (highlight vs clipboard)
  • Expect onselect on plain <div> content
  • Block text selection with user-select: none unnecessarily
  • Show alert() on every selection
  • Rely on onselect alone for rich-text editors — use dedicated APIs

Conclusion

The onselect attribute runs JavaScript when the user highlights text inside an input or textarea — useful for selection counts, formatting tools, and contextual form help.

Read the selection with selectionStart and selectionEnd, use addEventListener in production, and reach for selectionchange when you need page-wide selection handling.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onselect

Bookmark these before wiring selection handlers.

5
Core concepts
02

Highlight

Not copy.

When
🔢 03

selectionStart

Read range.

API
📋 04

oncopy

Clipboard.

Compare
🌐 05

selectionchange

Whole page.

Alternative

❓ Frequently Asked Questions

It runs JavaScript when the select event fires — when the user highlights text inside an input or textarea.
Text-like <input> elements and <textarea>. Plain paragraphs and divs use selectionchange on the document instead.
Use element.value.substring(element.selectionStart, element.selectionEnd) inside your handler.
onselect fires when text is highlighted. oncopy fires when the user copies to the clipboard (Ctrl+C or context menu).
addEventListener("select", handler) is preferred in production — easier to attach multiple listeners and keep HTML separate from behavior.
Yes in all modern browsers on input and textarea elements.

Build selection-aware forms

Practice the onselect attribute with textarea handlers and character counts in the Try It editor.

Try textarea example →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful