Tony
Tony

Reputation: 3

How to verify multiple OTPs using the prompt in browser?

I want to use the snippet below to verify multiple OTPs. If one OTP is correct, the user should be asked the next question. After 4 questions, show greetings.

var question = prompt('Who shot Abraham Lincoln?');

switch (question) {
    case 'john wilkes booth':
    case 'John Booth':
    case 'John Wilkes Booth':
        alert("That\'s Right!"); 
        window.location.href = 'q2.html'; 
        break;

    default:
        alert("Sorry, that\'s not right.");
        alert('Please try again');
        history.refresh();
        break;
}

Need help to re-build the code above.

Upvotes: 0

Views: 85

Answers (1)

nkshio
nkshio

Reputation: 1080

Solution below

var verificationStatus = 'unverified';
    
    function questionnaire(questions, answers) {
        // Proceed only if # of questions and answers are equal
        if (questions && answers && questions.length === answers.length) {
    
            questions.forEach(function(question, index) {
                // Prompt only if verificationStatus has not been marked false already
                if (verificationStatus !== false) {
                    var userInput = prompt(question);
    
                    switch (userInput) {
                        case answers[index]:
                            verificationStatus = true;
                            break;
    
                        default:
                            verificationStatus = false;
                            break;
                    }
                }
            });
        }
    
        if (verificationStatus) {
            alert('Greetings, Verification Successful');
        } else {
            alert('Sorry, Verification Failed');
        }
    }
    
    // Please note # of questions and answers must be equal
    questionnaire(['Q1', 'Q2', 'Q3', 'Q4'], ['1', '2', '3', '4']);

Behaviour

  • The snippet above asks 4 questions, to which answers are 1, 2, 3, 4 respectively.
  • If at any point, wrong answer is given, no more questions are asked.
  • A message (greetings) is displayed at the end.

Hope it helps!

Upvotes: 2

Related Questions