thenomadicmann thenomadicmann - 9 months ago 33
Javascript Question

jQuery - Making sure user doesn't submit same value in text input twice in a row

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();
});
});

Answer Source

Remove the var from the last line of your click handler function, because that is creating a local variable inside that function, and the value isn't retained between calls to the click handler. You want to be referring to the questionValue variable declared outside the click handler.

So change:

var questionValue = $("#submit").val();

...to:

questionValue = $("#submit").val();

EDIT: I just noticed that you are getting the value of an element with the id submit, the same element the click handler is bound to, which doesn't seem right. The button's value won't change between clicks. You don't show the HTML, so I'm not sure what the ID of the text box is, but you should double-check that selector in the if condition and on the line I've shown.