HTML onchange Event Attribute
Description
The onchange HTML event attribute fires when the value of an HTML element is changed. This can happen when the user changes the value of a form element, such as a text input, checkbox, or select element, or when the value of an element is changed by JavaScript code.
The onchange event is similar to the oninput event, but there are a few key differences. The oninput event fires immediately after the value of an element is changed, while the onchange event fires when the element loses focus. This means that the onchange event is only fired when the user has finished changing the value of the element.
Additionally, the onchange event also works on <select> elements, while the oninput event does not. This is because the value of a <select> element is not changed until the user selects an option and the element loses focus.
The onchange event can be used to perform a variety of tasks, such as:
- Validating form input
- Updating other elements on the page when the value of an element is changed
- Submitting a form when the user changes the value of a form element
- Performing calculations based on the value of an element
For example, the following code shows how to use the onchange event to validate the value of a text input field:
<input type="text" id="name" onchange="validateName()">
function validateName() {
var name = document.getElementById('name').value;
if (name === '') {
alert('Please enter your name.');
}
}
In this example, the validateName() function is called whenever the user changes the value of the name text input field. The function checks to see if the value of the field is empty. If it is, the function displays an alert message.
Syntax
<element onchange="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
Browser Support
The following information will show you the current browser support for the HTML onchange event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 14th October 2023
