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
    hi,

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

    upload_2022-7-4_8-53-45.png

    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'>
      <tbody>
        <tr>
          <td>&nbsp;</td>
          <td>19,433.33</td>
        </tr>
      </tbody>
    </table>
    HTML:
    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);
      counter++;
    } while (amount > cost);
    
    Code (JavaScript):
     
    sarahk, Jul 3, 2022 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Or to be a bit more "modern" about it.

    
    <table>
      <tbody id="calc">
        <tr>
          <td>1766.67</td>
          <td>19433.33</td>
      </tbody>
    </table>
    
    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...

    {
      const
        calc = document.getElementById("calc"),
        reduce = +calc.rows[0].cells[0].textContent;
      let
        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.

    https://codepen.io/jason-knight/pen/mdxVydY
     
    deathshadow, Jul 5, 2022 IP
    sarahk likes this.