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;
    }

}
1
  • 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. Commented Mar 11, 2016 at 19:03

3 Answers 3

1

You could use a method like this:

if (number != Math.round(number)){
    alert("Enter a whole number");
  }
Sign up to request clarification or add additional context in comments.

Comments

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?

2 Comments

And yet "100" === parseInt("100") returns false. So this method doesn't appear to work for strings that are valid integers from parseInt().
== compares the value, but === compares the value and types and, === in js is == in other languages.
0

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

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.