Onchange Event in JavaScript

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

The onchange is an event attribute. We can listen to the change event to perform the operation based on any change and the onchange attribute is used to associate the functionality for this event. The event is triggered whenever the value of the HTML element changes. The term value differs for several elements like, for input element the value is entered text, for select element the value is selected option, etc.

Syntax of Onchange Event in JavaScript

There are three main ways to specify this event in syntax. We'll go through each in turn.

Writing Onchange Event Attribute

Association of Events with the HTML Element

Select Element Object and then Attach Function to onchange Property

How does Onchange event in JavaScript work?

The onchange in javascript is an event attribute, and we write it inside the tag of the HTML element. The change in the value of an element triggers the change event, and subsequently, a function associated with the event gets executed in which we can perform some state manipulation to reflect the corresponding changes in the Document Object Model according to the last user interaction.

This event attribute falls into the category of Form Events. That's why onchange is used with form controls, like input, select, checkbox, radio buttons, etc. The Javascript listens for user input and fires this event whenever a value gets updated.

The onchange event attribute fires the event when the element loses focus.

Note: If there is a need to fire an event immediately after the change, then we should use the oninput event attribute.

Examples

In these examples, we are associating a function with the onchange event attribute. When the element's value is updated, and the element loses focus, the change event is fired, and subsequently, onchange triggers the execution of corresponding functionality.

Onchange with Text Input Element

Output: GIF1

Onchange with Select Element

Output: GIF2

Onchange with Radio Buttons

Output: GIF 3

Browser Compatibility

The onchange event attribute is supported by all major browsers like Chrome, Internet Explorer, Firefox, Safari, Opera, Edge, etc.

Conclusion

  • onchange is an event attribute.
  • It is used to associate functionality with being executed whenever the change event occurs.
  • A point worth noticing is, the event only gets fired when the element loses focus.