user5171952
user5171952

Reputation:

Function works with text input but not numerical input

I have a JavaScript function that clears a text input if an alphabet character is typed into it.

input = document.getElementById('inf');
input.onkeyup = function() {
  value = input.value;
  truth = isNaN(value);
  if (truth) {
    input.value = '';
  }

};
input {
  border: 2px solid black;
  margin-right: 10px;
}
<input type='text' id='inf' />Numbers Only
<br />Type a number in, and it stays. Put a letter in, and the input clears itself

The problem is, this does not work when the input type is set to number, as evidenced by the below sample.

input=document.getElementById('inf');
input.onkeyup=function(){
  value=input.value;
  truth=isNaN(value);
  if(truth){
    input.value='';
  }
  
};
input{
  border:2px solid black;
  }
<input type='number' id='inf'/>
<br />
As you can see, it doesnt work anymore.

My question is twofold:

1) Why does it work with a text input but not a number input?

2)Is there an easy fix? I need it as a number input, so that must stay the same.

Please Javascript answers only. No jQuery.

Upvotes: 2

Views: 88

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Number inputs don't allow non-numeric data, so this will always be false:

truth= isNaN(value);

Instead, you could check if the key pressed is a digit or a decimal:

input=document.getElementById('inf');
input.onkeyup=function(e) {
  if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
    input.value='';
  }
};
<input type='number' id='inf'/>

Upvotes: 1

Joy Biswas
Joy Biswas

Reputation: 6527

You can just check for blank along with your isNaN check

var truth = isNaN(value) || value==='';

Since the input type=number will convert any non numeric to blank

Upvotes: 0

James McDowell
James McDowell

Reputation: 2768

When input type is number, it returns null if there is a non-number character in the text.
So

"abc123" = ""  
"123abc" = ""  
"123" = "123"  


isNaN(null) is false.

Upvotes: 0

Related Questions