rid
rid

Reputation: 63452

Determining the contents of a number input

If I have an input of type number, how can I find out what the user typed if they didn't type a number?

<input type="number" onchange="console.log(this.value)">

The above shows an empty string if I type "a" in the input. How can I get the actual contents of the input?

Upvotes: 0

Views: 74

Answers (4)

Asim Dahal
Asim Dahal

Reputation: 147

You cannot get a text input from a input type number so,you can do it like this

in html

<input type="text" onchange="detectNumber(this.value)" id = 'number_input'">

in js

let numberInput = document.querySelector('#number_input');
function detectNumber(value){
  if(isNaN(parseInt(value))){
     console.log('Text input!!')
     numberInput.value = value.split('').pop().join('');
  }

}

Upvotes: 0

ricksclick
ricksclick

Reputation: 21

You can use any of the below events:

onkeyup = "console.log(event.key)"
onkeypress = "console.log(event.key)"
onkeydown = "console.log(event.key)"

But these will trigger as soon as they enter a key value.

In your use case, user will never be able to actually enter anything other than numbers into the input element as it is set as type="number". You can try using type="text", to differentiate values between numbers and other characters.

Upvotes: 1

Mohammad Malek
Mohammad Malek

Reputation: 634

This is the example of type:number did not type a any text or charterer only allowed number you can check this

<input type="number" oninput="console.log(this.valueAsNumber)">

Upvotes: 2

obscure
obscure

Reputation: 12891

I'm afraid there is no way since it's meant to accept numbers only. However you could at least retrieve if the user didn't enter a number by switching to the oninput event and evaluating valueAsNumber though.

So

<input type="number" oninput="console.log(this.valueAsNumber)">

will return NAN if it ain't a number.

Upvotes: 0

Related Questions