Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onchange — handling a change event

The onchange attribute contains JavaScript that runs for a change event. For form controls, this represents a committed user change, not necessarily every edit to the value.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

onchange="JavaScript statements"

onchange is an event handler content attribute for change. Its value is a JavaScript function body, not a script URL. The attribute is available on all HTML elements, but adding it does not itself make an element generate change.

Event timing depends on the control. A checkbox emits change when the user toggles it; a text field typically does so when its changed value is committed by leaving the field. Use input to react to ongoing edits. Assigning .value or .checked in JavaScript does not automatically emit change.

Inside the attribute code, this refers to the element handling the event, and event provides the event object. The JavaScript counterpart is the element.onchange property; another assignment replaces that mechanism's previous function. element.addEventListener('change', handler) registers independent listeners. Content Security Policy can block attribute code, so use an allowed script with addEventListener() in that environment.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onchange example</title>
<label>
  <input type="checkbox" onchange="document.getElementById('state').textContent = this.checked ? 'ON' : 'OFF'">
  Enabled
</label>
<p id="state" role="status">OFF</p>
</html>

Result

OFF → ON → OFF

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources