Change event (DOM, Javascript)

Devtool Chrome Event Listener

About

change is an event that is fired when:

  • a control loses the input focus
  • and its value has been modified since gaining focus.

Attribute

You can attach a callback function to the change event with the onchange attribute.

This attribute applies only to the following elements:

Example

Radio

An example with a two radio element that will fire the change event when choosing one or the other.

  • A serie of radio input with the same name (ie choice) and different value
<p>Select a radio to fire the change event</p>
<p><input type="radio" name="choice" id="choice1id" value="choice1" onchange="return handleChange(this);"><label for="choice1id">choice 1</label></p>
<p><input type="radio" name="choice" id="choice2id" value="choice2" onchange="return handleChange(this);"><label for="choice2id">choice 2 </label></p>
  • The callback to handle the change event.
let handleChange = (element) => {
   console.log("The event "+event.type+" was fired and the input radio button chosen has the value "+element.value);
}

Typescript and TS2339 error

To not get the error:

TS2339: Property 'value' does not exist on type 'EventTarget & Element'.

You need to define the type of element for the change event

Example for a select element and React

import {ChangeEvent} from "react";

function handleChange(event: ChangeEvent<HTMLSelectElement>) {

   const selectValue = event.target.value;

}





Discover More
Devtool Chrome Event Listener
DOM - Event Type (name)

An event is categorize by its type which is a property of the event object The type of an event is also known as the name of the event (Ref)...
Html Radio Illustration
HTML - Radio

A radio represents a serie of mutually-exclusive choices in a form. It is an input element of type radio. A radio is round to distinguish from the square checkbox. As the checkbox, the state...
How to create a Debounce Function in Javascript?

A debounce is a function that: will wrap a callback function willnot let the callback function execute for each event will let the callback function execute only when a certain amount of time...
Html Input File Multiple Warning Dialog
How to handle files in Javascript with the File API of the Browser?

The file api is a browser javascript api that allows file system operation in the browser. FileApiopeneditsave Uploading a file: You can open and read files via the input of type file The...



Share this page:
Follow us:
Task Runner