I have to check (prompt window is obligatory) if a user entered a correct answer on these conditions:
- If a user entered a correct answer, alert 'you are correct'.
- If a user enters a wrong answer OR leaves it EMPTY, alert 'you are wrong' 3 If a user presses the cancel button nothing happens.
var num1 = Math.floor(Math.random() * 9 + 1);
var num2 = Math.floor(Math.random() * 9 + 1);
var result = num1 * num2;
var userInput = parseInt(prompt('What is ' + num1 + ' * ' + num2 + ' ?'));
if (userInput === result){
alert('You are correct!');
} else if (userInput === '' || userInput !== result) {
alert('You are wrong!');
} else if (userInput === null) {
alert('Cancelled!');
}
What happens is that alert says 'you are wrong' even if I press cancel. I added cancelled alert just for an example. Any suggestions?
prompt()does indeed returnnullwhen the user clicks Cancel, this information is lost when passed throughparseInt(). You should check for thenullresponse before attempting to parse the result.