2

I have an input field and one button. When the user clicks the button, first I check whether they entered a number or not. If it is a non-numeric string then nothing should happen. If it's a number then I will do some modification to the above gray div. When I enter a number and log its type to the console, it shows that the data type of the value is "string." So how do I check for the correct data type?

Here is the code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id='test'></div>
  <p><input type='text' id='myText'/>
  <input type='button' value='click' id='myButton'/></p>
</body>
</html>

CSS

#test {
  width: 200px;
  height: 200px;
  background: gray;
}

JavaScript

var el = document.getElementById('myButton'),
    elOne = document.getElementById('myText'),
    container = document.getElementById('test');

el.onclick = function(){
  var data = elOne.value;

  if(typeof data === 'number'){
    console.log('number');
  }else if(typeof data === 'string') {



     console.log('string');
  }
};

And here is the jsbin link - http://jsbin.com/hequr/1/

8
  • 3
    .value always returns a string. Commented Feb 23, 2014 at 8:46
  • ok, but how to convert back to number, if user enter a number. Commented Feb 23, 2014 at 8:47
  • 1
    @FelixKling, when type="text" Commented Feb 23, 2014 at 8:48
  • -> How do I Convert a String into an Integer in JavaScript? Commented Feb 23, 2014 at 8:48
  • Even with the input type number, .value will return a string. Just the user presentation of the input changes. Commented Feb 23, 2014 at 8:54

1 Answer 1

0

use functions like isNaN() or isNumeric() or use Regular expression \[0-9].*\

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

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.