Home Writing

til / use valueAs* on inputs

If you want to get the value of an input as a number or a date, you could parse the value of a text input. However, there’s an easier solution by using valueAsNumber or valueAsDate. The attributes are only available for certain input types and return NaN if not available or if the value is invalid.

Browser support is great, valueAsNumber is supported by all browsers (even IE) and valueAsDate is supported by all browsers except IE.

 1<!—- This will always return NaN since valueAsNumber is not available on text inputs —->
 2<input type="text" onChange={e => console.log(e.target.valueAsNumber)} />
 4<!—- Return the value as an integer or a
 5float depending on the input's step attribute —->
 6<input type="number" onChange={e => console.log(e.target.valueAsNumber)} />
 8<!—- Return the date as a UNIX timestamp, i.e. new Date().getTime() —->
 9<input type="date" onChange={e => console.log(e.target.valueAsNumber)} />
11<!—- Return the date as a JS Date object —->
12<input type="date" onChange={e => console.log(e.target.valueAsDate)} />

  • MDN. (2021-11-10). HTMLInputElement. Link
  • Can I Use. (2021-11-10). HTMLInputElement API: valueAsNumber. Link

  • Loading next post...
  • Loading previous post...