vendredi 22 septembre 2017

How to generate a random number and assign it to my variable array in JavaScript?

I need to create a magic 8 ball web page that generates a random response when a question is typed and they click the button. So far I have the HTML and CSS done:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Magic 8 Ball</title>
    <link rel="stylesheet" href="styles.css">
    </head>
    <body>
    <div id="wrapper">
    <header>
        <h1>Magic 8 Ball</h1>
    </header>
        <h3>What would you like to know?</h3>
        <input type="text" name="txtQuestion" id="txtQuestion">
        <br />
        <input type="button" id="btnAsk" value="Ask the 8 Ball">
        <h3>The 8 Ball says:</h3>
        <h3 id="Response">Ask the 8 Ball a question...</h3>
    </div>
    <script src="scripts/jquery-3.2.1.js"></script>
    <script src="scripts/my_scripts.js"></script>
    </body>
    </html>

I have been working on the JavaScript, but nothing I do seems to generate anything! Here is my code:

    $(document).ready(function() {
    $("button").click(function()
    {
    var answer;
    var my_num = getRandom(14);
    var responses = Array(15);
    responses[0] = "Ask again later...";
    responses[1] = "Yes";
    responses[2] = "No";
    responses[3] = "It appears to be so";
    responses[4] = "Reply is hazy, please try again";
    responses[5] = "Yes, definitely";
    responses[6] = "What is it you really want to know?";
    responses[7] = "Outlook is good";
    responses[8] = "My sources say no";
    responses[9] = "Signs point to yes";
    responses[10] = "Don't count on it";
    responses[11] = "Cannot predict now";
    responses[12] = "As I see it, yes";
    responses[13] = "Better not tell you now";
    responses[14] = "Concentrate and ask again";

    var RandNum = Math.floor(Math.random()*14);

    var answer = responses[RandNum];

    $("#Response").replaceWith(answer);
    });
    });

I honestly don't know what I am doing wrong. I thought I should create a new array with all the possible responses. Then I generate a random number, and assign that to the array variable to give me a random response. Then I replaced the h3 tag that exists with the response I randomly generated. Sounded good in theory. Yet nothing works when I go to click the button. Even if I manually assign a response, say answer = responses[5], nothing happens. What am I missing here?




Aucun commentaire:

Enregistrer un commentaire