Click here to Skip to main content
15,895,740 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to create a simple program where a user needs to pick a maximum number, then try to guess a number between 1 and that maximum number. When they enter their guess, I need to validate the input, and offer a choice of feedback: different messages if it's (1) not a number, (2) a number not within the range, (3) the correct guess, (4) too high, but within range, and (5) too low, but within range.

What I have tried:

JavaScript
function do_guess(prompt) {
    let valid_input = false;
    let guess = Number(document.getElementById("guess").value);

    let message = document.getElementById("message");

    while(!valid_input) {
        input = window.prompt(prompt);

        guess = Number(input);
    
        if (guess == NaN) {
            message.innerHTML = "That is not a number!";
        }
        else if (guess < 1 || guess > val) { \\val is maximum range - I'm not sure how to code this yet\\
             message.innerHTML = "That number is not in the range, try again.";
        }
        else if (guess == num) {
            valid_input = true;
            message.innerHTML = "You got it!";
        }
         else if (guess > num) {
            message.innerHTML = "No, try a lower number.";
        }
        else {
             message.innerHTML = "No, try a higher number.";
        }
    }    
}
Posted
Updated 12-Nov-20 5:39am
v2
Comments
Richard MacCutchan 9-Nov-20 12:24pm    
What is the problem?
DerekT-P 9-Nov-20 12:56pm    
So what is this code doing that you don't want it to, or not doing that you do? (BTW, use guess.isNaN rather than guess == NaN ).
Hint - one problem you will face is that the browser may not repaint the "message" element because redrawing only occurs once script execution completes, and in your code it doesn't complete (exit the while loop) until the user enters the correct guess. (Waiting at the prompt for user input doesn't count as exiting script execution). Research how to resolve that problem, or restructure your code so that it's not all within a single while loop.

1 solution

Rethink your logic (implied in the first two comments):

Use something like an <input> element for the data entry. Use a button, for example, to trigger a test of the contents of the box and display your message.

In this way, the javascript is only executed when it needs to perform it's test.

Other options, instead of a button, would be an 'onblur" event, which would trigger your javascript when the focus leaves the input box.

Bonus points: create the input box so that it only accepts numeric input (hint: onkeyup is a help in testing after each character .
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900