thenomadicmann thenomadicmann - 9 months ago 26
Javascript Question

Changing text of an element with jQuery with click event. It changes back an instant later

I'm building a Magic 8 Ball page and every time I click the submit button on my page the text in my heading #eightBallAnswer changes to one of my random answers for a fraction of a second then changes back to the original text in my HTML. I've tried this in multiple browsers. Some insight would be greatly appreciated.

Here is my jQuery:

$(document).ready(function(){
$("#submit").click(function() {

//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]);
});
});

Answer Source

That's cause your form is submitting and the page refreshing :)

Use event.preventDefault()

$(document).ready(function(){
    $("#submit").click(function( event ) {

        event.preventefault();

        //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]);
    });
});