I'm creating a magic 8 ball app where the the user enters a question in an input box. They press the submit button and the answer replaces the default html text in a heading. If the same question is asked twice in a row I want to display an alert message instead of giving a new answer. I'm new to jQuery and I can't quite figure out how to store the last value entered. I would really appreciate some input. Thank you in advance.
$(document).ready(function(){
var questionValue;
$("#submit").click(function() {
//Make sure user doesn't ask same question twice in a row
if (questionValue != $("#submit").val()) {
//List of possible responses
var response = ["Ask again later…", "Yes", "No", "It appears so", "Reply is hazy, please try again", "Yes, definitely", "What is it you really want to know?", "Outlook is good", "My sources say no", "Signs point to yes", "Don't count on it", "Cannot predict now", "As I see it, yes", "Better not tell you now", "Concentrate and ask again"];
//generate a random number between 0-14
var randomNumber = Math.floor(Math.random() * 15);
//Present random answer
$("#eightBallAnswer").text(response[randomNumber]);
}
else {
alert("Ask a different question");
}
var questionValue = $("#submit").val();
});
});
var randomNumber = Math.floor(Math.random() * response.length);; Don’t hard-code the length of the string. Also, definevar response=[…]before theclick()function. Otherwise you’re redefining the same array every time.