0

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")?

4
  • Input type number is simply parsing 123. as the integer 123. Why do you need the period? Commented Aug 24, 2018 at 11:50
  • 2
    Because the input type is number and 123. or 123.. is not a valid number Commented Aug 24, 2018 at 11:51
  • 1
    Not sure what people think about this, but... I personally dislike number inputs a lot! They always give a headache when you want some control over them. My suggestion is to use a "normal" input and add a regex that only allows numbers (and decimals if u want that). Commented Aug 24, 2018 at 11:54
  • 1
    @Chris I agree, I think I'll just use text input instead, otherwise I'll need a lot of number-specific logic. Commented Aug 24, 2018 at 14:04

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Regardless of what magic auto formatting JS does, there should be a way to get the exact input that was typed.
According to W3: "User agents must not allow the user to set the value to a non-empty string that is not a valid floating point number". So no there is not :) more info here: w3.org/TR/2011/WD-html5-20110525/number-state.html#number-state
0

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.

Comments

0

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 );   
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.