Change events on form elements

  • React
  • Examples
  • Change events on form elements

React example • 2 min read

  • Events
  • Forms

Here you can find some code samples on how to get the current value when the change event is called in textarea, select, and input elements. Notice that we get this value from event.target.value in all cases except in the input[type="checkbox"] where we do it using event.target.checked instead, in order to check if it checked or not.

Textarea

<textarea
  onChange={(event) => {
    console.log(`Value changed on textarea: ${event.target.value}`);
  }}
/>

Select

<select
  onChange={(event) => {
    console.log(`Value changed on select: ${event.target.value}`);
  }}
>
  <option>Red</option>
  <option>Green</option>
  <option>Blue</option>
</select>

Input

<input
  onChange={(event) => {
    console.log(`Value changed on input: ${event.target.value}`);
  }}
/>

Input type="search"

<input
  type="search"
  onChange={(event) => {
    console.log(`Value changed on search: ${event.target.value}`);
  }}
/>

Input type="checkbox"

<input
  type="checkbox"
  onChange={(event) => {
    console.log(`Value changed on checkbox: ${event.target.checked}`);
  }}
/>

Input type="radio"

<label htmlFor="radioA">Radio A</label>
<input
  type="radio"
  name="radioExample"
  id="radioA"
  value="A"
  onChange={(event) => {
    console.log(`Value changed on radio: ${event.target.value}`);
  }}
/>
<label htmlFor="radioB">Radio B</label>
<input
  type="radio"
  name="radioExample"
  id="radioB"
  value="B"
  onChange={(event) => {
    console.log(`Value changed on radio: ${event.target.value}`);
  }}
/>

Input type="color"

<input
  type="color"
  onChange={(event) => {
    console.log(`Value changed on color: ${event.target.value}`);
  }}
/>

Input type="date"

<input
  type="date"
  onChange={(event) => {
    console.log(`Value changed on date: ${event.target.value}`);
  }}
/>

Input type="time"

<input
  type="time"
  onChange={(event) => {
    console.log(`Value changed on time: ${event.target.value}`);
  }}
/>

Input type="week"

<input
  type="week"
  onChange={(event) => {
    console.log(`Value changed on week: ${event.target.value}`);
  }}
/>

Input type="range"

<input
  type="range"
  min={0}
  max={100}
  step={10}
  onChange={(event) => {
    console.log(`Value changed on range: ${event.target.value}`);
  }}
/>

Example: https://codesandbox.io/s/ky3jxi