Home > OS >  Why does this genorater code not work in JavaScript?
Why does this genorater code not work in JavaScript?

Time:08-05

I am trying to create a simple genorator code for a flight simulator. It should genorate four numbers between 0 and 7, and then update the text of a Div.

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SG 0.0.0</title>
    <script src="index.js"></script>
</head>
<body>
    <div id="squawk">0000</div>
    <button onclick="genSquawk" id="gen">Genorate Squawk</button>
</body>
</html>

JS:

const div = document.getElementById('squawk')

var num1 = Math.random() * 7;
var num2 = Math.random() * 7;
var num3 = Math.random() * 7;
var num4 = Math.random() * 7;

function genSquawk() {
    div.textContent = num1,num2,num3,num4;
}

CodePudding user response:

div.textContent = num1,num2,num3,num4; is not valid syntax. If you want an an array, for instance, you could use [num1, num2, num3, num4]. Since you're updating the node's text content, you likely want to make these numbers a string value to insert into your div element. In that case, there are many ways to make a string from your series of numbers. One way is string concatenation, something like

div.textContent = `${num1}, ${num2}, ${num3}, ${num4}`;

CodePudding user response:

There are a few changes to be made. One is the following line:

<button onclick="genSquawk" id="gen">Genorate Squawk</button>

You are referencing the genSquawk function on the onclick property, not calling it. The correct is:

<button onclick="genSquawk()" id="gen">Genorate Squawk</button>

Now it should trigger the function properly. The second one is: the syntax num1,num2,num3,num4 is not correct, and will cause the code to display only the first num. In order to do so, use string literals: ${num1}, ${num2}, ${num3}, ${num4}.

Finally, I do not know if you want integers or if each of the four numbers could be floats. But I added a function to generate a int number between 0 and 7.

function getRandomArbitrary() {
  return Math.floor(Math.random() * 7);
}

function genSquawk() {

  const div = document.getElementById('squawk')
  var num1 = getRandomArbitrary();
  var num2 = getRandomArbitrary();
  var num3 = getRandomArbitrary();
  var num4 = getRandomArbitrary();
  div.textContent = `${num1}${num2}${num3}${num4}`;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SG 0.0.0</title>
  <script src="index.js"></script>
</head>

<body>
  <div id="squawk">0000</div>
  <button onclick="genSquawk()" id="gen">Genorate Squawk</button>
</body>

</html>

  • Related