0

I am building little app with JS and I find difficult with that:

I want to get from users input an integer number from range 0-100. If it's not an int I am parsing it to int. Then I want to put that number to function checkNum, and there appears a problem. Let me paste my code:

$(function () {

initApp();

function getInput(){
    var userInput = window.prompt("Input number from range 0-100");
    var num = parseInt(userInput);
    return num;
};


function checkInput(num){
    if( num < 0 || num > 100){
        displayError();
    }
    else{
        alert('num is ok');
    }
};

function displayError(){
  alert("error");
};

function initApp(){
    getInput();
    checkInput();
};

});

As you can see even if I put number out of range there is always alert says num is ok - what is not true. I have no idea what I am doing wrong. I'll appreciate any help. What is more, I'd like to put here function Number.isNaN() to provide typing non-sense in the input. I thought about statement like this:

if(Number.isNaN(num) || num <0 || num > 100){...}

I guess that my mistake is obvious and trivial for someone more experienced than me.

1
  • 1
    This is unrelated to your question, but should always explicitly set the second parameter of parseInt(): parseInt(userInput, 10); Commented Jul 25, 2016 at 16:53

3 Answers 3

1

To answer your question, you're passing nothing to checkInput() so it's always undefined, and undefined < 0 || undefined > 100 is always false. The solution is to pass the returned value from getInput() to checkInput() like so:

function initApp(){
    var value = getInput();
    checkInput(value);
}

To answer what you're aiming for: use <input type="number"> and have the browser do the work for you.

<form>
  <input type="number" min="0" max="100" step="1" />
  <button>Try to submit!</button>
</form>

No JavaScript required.

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

Comments

0

You need to pass the return value from getInput into checkInput:

function initApp(){
    checkInput(getInput());
}

Side note: Function declarations (what you've used) don't need ; at the end.

Comments

0

You just need to give the value returned by getInput like this ;)

initApp();

function getInput(){
    var userInput = window.prompt("Input number from range 0-100");
    var num = parseInt(userInput);
    return num;
};


function checkInput(num){
    if( num < 0 || num > 100){
        displayError();
    }
    else{
        alert('num is ok');
    }
};

function displayError(){
  alert("error");
};

function initApp(){
    var value = getInput();
    checkInput(value);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.