About
change is an event that is fired when:
- 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:
- and TEXTAREA.
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;
}