0

The problem is, I have no idea why this code doesn't work. I searched everywhere!
What this code does, is to take information from a number box, then display a message if the users inputs text(an error), and display a success message, if the user inputs number.
HTML ->

<input type="number" id="number">
<button onclick="makeTrack()">Make Track</button>
<div><div>

JS -> Where the problem starts!

function makeTrack() {
    var e = document.getElementById("number").value;
    if(typeof e === "number";) {
        alert("It works!");
    } else if(typeof e === "string") {
        alert("Please input a number!");
    }
}
  • All values you grab from an element are of type string. You probably want to check if `isNaN` and act accordingly – elclanrs Sep 05 '14 at 22:26

1 Answers1

4
document.getElementById("number").value

The value of all elements will always be a string; JS doesn't try to outsmart you and guess whether it's a number or not (that would be disastrous!). Try parsing it first, like this:

function makeTrack() {
    var e = parseInt(document.getElementById("number").value, 10);
    if(!isNaN(e)) {
        alert("It works!");
    } else {
        alert("Please input a number!");
    }
}

Note that this will interpret an input of "12345 this is a string" as 12345. If this is undesirable, try something like this:

var e = document.getElementById("number").value;
if (/^[0-9]+$/.test(e)) {
    // good
    e = parseInt(e, 10); // make sure to still convert it to a number!
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • While the first part of your answer is correct, simply checking `isNaN` is not enough. See here for more info on number testing in javascript: http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric – Travis J Sep 05 '14 at 22:39
  • It works pretty well, the problem with it is that: it doesn't alert(), if it's isn't a number(once you press the button). By the way, this is still pretty useful, thanks. –  Sep 06 '14 at 23:01