1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

How can i do this using javascript array and loop

Discussion in 'JavaScript' started by neilfurry, Jul 3, 2022.

  1. #1

    i have this problem. Is there a way i can create this using javascript loop and array.


    as you can see, when i input 19,433.33 it will be subtracted by 1,766.67, then the difference will be displayed to the right which is 17,666.67, then subtracted again by 1,766.67. it will just do this until it reaches 0.00
    Can you enlighten me on how this will work using array and loop in javascript?

    Thank you
    Solved! View solution.
    neilfurry, Jul 3, 2022 IP
  2. #2
    This should do the trick: https://codepen.io/itamer/pen/MWVwGeV

    <table id='myTable' border='1' cellspacing='0' cellpadding='5'>
    let amount = 19433.33;
    let cost = 1766.67;
    let table = document.getElementById("myTable");
    let counter = 1;
    do {
      amount = amount - cost;
      var row = table.insertRow(counter);
      // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      // Add some text to the new cells:
      cell1.innerHTML = cost;
      cell2.innerHTML = amount.toFixed(2);
    } while (amount > cost);
    Code (JavaScript):
    sarahk, Jul 3, 2022 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Likes Received:
    Best Answers:
    Trophy Points:
    Or to be a bit more "modern" about it.

      <tbody id="calc">
    Code (markup):
    Then extract the value from the markup, and not use the possibly insecure and always slow innerHTML and instead use textContent like a good little doobie...

        calc = document.getElementById("calc"),
        reduce = +calc.rows[0].cells[0].textContent;
        total = +calc.rows[0].cells[1].textContent;
      while (total > 0) {
        total -= reduce;
        let tr = calc.insertRow();
        tr.insertCell().textContent = reduce.toFixed(2);
        tr.insertCell().textContent = total.toFixed(2);
    Code (markup):
    Also skipping a bunch of "variable for nothing" and showing the negative result.

    deathshadow, Jul 5, 2022 IP
    sarahk likes this.