1

Recently I have been working on a "spinner" that increases and decreases a number by 1 each time, however I've wanted to add validation to the program so that integers only are accepted (no decimals) however I've been unsuccessful in doing this.

I've researched the use of NaN and parseValue(s) but I've not found a way of including this to my script, and any help would be highly appreciated. All code in the example given works as I want it to, therefore I only need the validation.

CODE: HTML

<!DOCTYPE html>
<html>
    <head>
        <h1>Spinners in JavaScript</h1>
    </head>
    <body>
        <p id="textDisplay()">0</p>

        <div align="middle">
            <button onclick="spinUp()">+1</button>
            <button onclick="spinDown()">-1</button>
        </div>
    </body>
</html>

JavaScript

currentNumber = 0;

function spinUp() {
    if(currentNumber==100){
    currentNumber = 0;
    document.getElementById("textDisplay").innerHTML = currentNumber;

    } else if(currentNumber < 100) {
    currentNumber++
    document.getElementById("textDisplay").innerHTML = currentNumber;
    }
}

function spinDown() {
    if(currentNumber>0){
    currentNumber--;
    document.getElementById("textDisplay").innerHTML = currentNumber;

    } else if(currentNumber<=0){
    window.alert("Too low! Higher!");
    currentNumber++;
    document.getElementById("textDisplay").innerHTML = currentNumber;
    }

}
Daniel
  • 9,491
  • 12
  • 50
  • 66
Matt Rogan
  • 55
  • 6
  • Stuff and data you get from the DOM (Basically data from html tags, attributes, etc...) are all strings, you must convert them to integers, with parseInt(string, base), base is 10 by default. – Noctisdark Mar 11 '16 at 19:03

3 Answers3

1

You could use a method like this:

if (number != Math.round(number)){
    alert("Enter a whole number");
  }
Matt
  • 63
  • 2
  • 12
0

You can use the === operator as below :

if (data === parseInt(data, 10))
    alert("data is integer")
else
    alert("data is not an integer")

How to check if a variable is an integer in JavaScript?

Community
  • 1
  • 1
bugyt
  • 616
  • 4
  • 11
  • And yet "100" === parseInt("100") returns false. So this method doesn't appear to work for strings that are valid integers from parseInt(). – Yogi Mar 11 '16 at 19:30
  • == compares the value, but === compares the value and types and, === in js is == in other languages. – Noctisdark Mar 11 '16 at 19:43
0

v === v | 0;
this is true if v is an integer, false otherwise.

Noctisdark
  • 350
  • 3
  • 17