Leo Jiang
Leo Jiang

Reputation: 26253

Why doesn't event.target.value include "." and "e" for number inputs?

I'm using Preact:

<input type="number" onKeyup={event => console.log(event.target.value)} />

If I enter a period or an "e", it doesn't appear as part of event.target.value until I enter another digit after it.

E.g.

If the input value is 123, 123 gets logged.

If the input value is 123., 123 gets logged.

If the input value is 123.., 123 gets logged.

If the input value is 123.4, 123.4 gets logged.

Why does it behave like this? Is there a way to get the actual input (without removing type="number")?

Upvotes: 0

Views: 3527

Answers (3)

front_end_dev
front_end_dev

Reputation: 2056

You can store the default value in a variable and update that variable after each keyup event.

example HTML

<input type="number" onKeyup={event => this.eachKeyPress(event)} />

JS

let output = "";
function eachKeyPress(event){
  output += event.key;
  console.log("value : ",output );   
}

Upvotes: 0

Kai L&#252;ck
Kai L&#252;ck

Reputation: 197

the point is that e is an expression e² is the same like e2, without any digit after e it is incomplete and the number won´t changed, so "e" isn't saved.

Same with the point. A number with point at the end is the number itself, so it won´t be saved.

You have to change it to text or your "e" at the last of this row isn't saved.

Upvotes: 0

Alen Genzić
Alen Genzić

Reputation: 1418

The number input can hold integers as well as floating point numbers.

Since 123. is an integer, the input will return the integer 123

Also 123.4 is a valid floating point number so the input will have a value of 123.4

There is no way to return strings such as 123.4 from a number input type because it is not meant to be used for that.

Upvotes: 2

Related Questions