Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to populate a table with a number that increments

I am attempting to keep track of how many times someone has flipped a coin and which side it was.

I do not understand how to get the number to increment itself nor get the table to get the row to populate with the div result appropriately. There is a space between the first instance and the second where it does not record heads or tails.

HTML

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<button id="flip" type="button" onclick="addRow()">Flip the coin</button>
  <div id="result"></div>

  <table id="myTable">
    <tr>
      <th>Flips</th>
      <th>Results</th>
    </tr>
    <tr>
      
    </tr>
    <tr>
      
    </tr>
  </table>

Script for Coin Flip

let button = document.getElementById("flip");
let result = document.getElementById("result");

function fnClick(event) {
  let num = Math.random();

  if (num < 0.5) {
    result.innerHTML = "You got HEAD";
  } else {
    result.innerHTML = "You got TAIL";
  }
}

Script For New Row

function addRow() {
  var number = 0;

  for (var i = 0; i < 10000; i++) {
    number++;
    console.log(number);
  }
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = i;
  cell2.innerHTML = result.innerHTML;
}
button.addEventListener("click", fnClick);

I would like to add a number to the left of my table progressively as the user clicks the coin flip as well as keep track of the results on the right side of the table.
How do I do this?

>Solution :

Update your addRow function like this and move the number variable outside to make it global

 var number = 0;
function addRow() {
  number++;
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = number;
  cell2.innerHTML = result.innerHTML;
}
button.addEventListener("click", fnClick);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading