Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a returned value in an html page

I just started learning javascript and followed an exercise on codeacademy to make a text base rock paper scissors game. I wanted to show it to someone, outside of the debug console but I can't figure out how to display it in an html page.

The code in my html file is:

<HTML>

    <HEAD>
        <script src="rockpaperscissors.js"></script>
    </HEAD>

    <BODY>Choose rock, paper or scissors and write your choice in the text box
        <p>
             <A HREF="javascript:processOrder();">Click here to begin</A>
    </p>
    ...
    </BODY>
</HTML>

and the code in my JS is:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if (computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

var compare = function (choice1, choice2) {
    if (choice1 === choice2) return "The result is a tie!";
    if (choice1 === "rock") {
        if (choice2 === "scissors") return "rock wins";
        else return "paper wins";
    }
    if (choice1 === "paper") {
        if (choice2 === "rock") return "paper wins";
        else return "scissors wins";
    }
    if (choice1 === "scissors") {
        if (choice2 === "rock") return "rock wins";
        else return "scissors wins";
    }
};

compare(userChoice, computerChoice);

I get the prompt to choose rock paper or scissors but it does not return anything after that. I don't see the computer choice in the html and I don't know what to use to show it.

like image 467
Cherry Avatar asked Jan 20 '26 11:01

Cherry


1 Answers

One easy way is to put an element with an id in your html:

<div id="ret"></div>

You can then change the last line of your javascript to:

document.getElementById("ret").innerHTML=compare(userChoice,computerChoice);

That will put the result inside of that div.

Or you could just do:

document.write(compare(userChoice,computerChoice));

Which will write the result where you put your script tag.

like image 179
ejk314 Avatar answered Jan 22 '26 01:01

ejk314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!