crashprophet
crashprophet

Reputation: 327

Adding two variables in javascript surrounded by HTML

I have stored two variables that generate simulate two random die rolls. I'm trying to add them in another paragraph like in the following; however, the line that adds them generates a "NaN". Any suggestions?

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <title>Rolling Two Dice</title>
  </head>
  <body>
    <p>Your first die rolled a <script>var roll1 = document.write(1 +
    Math.floor(6 * Math.random()))</script>.</p>
    <p>Your second die rolled a <script>var roll2 = document.write(1 +
    Math.floor(6 * Math.random()))</script>.</p>
    <p>The total of your rolls is <script>document.write(roll1 +roll2)</script>.</p>
</body>
</html>

Upvotes: 0

Views: 757

Answers (3)

BNL
BNL

Reputation: 7133

You need to assign the values to the variables then write the variables to the document.

<script>var roll1 = 1 + Math.floor(6 * Math.random());  document.write(roll1)</script>

I'd also suggest moving all of the script to a single block, as shown by jbabey. so you dont have little lines of JS all over your html. Use javascript in the single block to update the contents of a span with the values.

Upvotes: 0

Makita
Makita

Reputation: 1812

As per your sample:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Rolling Two Dice</title>
    <script>
        var roll1 = 1 + Math.floor(6 * Math.random());
        var roll2 = 1 + Math.floor(6 * Math.random());
        var total = roll1 + roll2
    </script>
</head>
<body>
<p>Your first die rolled a <script>document.write(roll1)</script>.</p>
<p>Your second die rolled a <script>document.write(roll2)</script>.</p>
<p>The total of your rolls is <script>document.write( total )</script>.</p>
</body>
</html>

The issue was mainly:

<script>var roll1 = document.write(1 + Math.floor(6 * Math.random()))</script>

document.write does not return a value you can assign to a variable.

Upvotes: 0

jbabey
jbabey

Reputation: 46647

Store the numbers, not the return from document.write (I have no idea what it returns). Also, i've seperated your HTML from your javascript, as using document.write is not a good habit to be in and mixing functional code (javascript) with presentational code (HTML) is a bad practice.

HTML:

<body>
    <p>Your first die rolled a <span id="roll1"></span>.</p>
    <p>Your second die rolled a <span id="roll2"></span>.</p>
    <p>The total of your rolls is <span id="total"></span>.</p>
</body>

JS:

var roll1 = 1 + Math.floor(6 * Math.random());
var roll2 = 1 + Math.floor(6 * Math.random());
var total = roll1 + roll2;
document.getElementById('roll1').textContent = roll1;
document.getElementById('roll2').textContent = roll2;
document.getElementById('total').textContent = total;

*Note that the textContent property will not work with some browsers.

Upvotes: 2

Related Questions