chiecoman
chiecoman

Reputation: 25

How to Append Increments in a Function Individually to a List?

My issue is I am not sure how to type the code to increment trainADistance by trainAMPM and decrease trainBDistance by trainBMPM in the do loop while having each text appended to the list. Each minute is supposed to be appended individually with text += "Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2);. An example is listed below. Any help would be appreciated.

What the function is supposed to do?

The function I have been attempting to create is supposed to allow the user to input three variables trainAMPH, trainBMPH and distanceApart. When the inputs are submitted, the function function calculateTrains() is supposed to calculate trainAMPH, trainBMPH into miles per minute trainAMPM and trainBMPM. There is a do-while loop in place to increment the minutesi , increment trainADistance by trainAMPM and decrease trainBDistance by trainBMPM. trainBDistance is supposed to contain the same value as distanceApart. The loop continues while(trainADistance < trainBDistance) and is supposed to append text into a list until the loop is broken. An example is listed below.

This is an example of what is supposed to be appended to to the list with inputs 70 for train A, 60 for train B and 260 for distance

•   Minute 1 Train A Position: 1.17 miles Train B Position: 259.00 miles
•   Minute 2 Train A Position: 2.33 miles Train B Position: 258.00 miles
•   Minute 3 Train A Position: 3.50 miles Train B Position: 257.00 miles
•   Minute 4 Train A Position: 4.67 miles Train B Position: 256.00 miles
•   Minute 5 Train A Position: 5.83 miles Train B Position: 255.00 miles

My Code

<script>
        function calculateTrains(){

            let trainAMPH= document.getElementById("trainAMPH").value;
            let trainBMPH= document.getElementById("trainBMPH").value;
            let distanceApart = trainBDistance = document.getElementById("distanceApart").value;
            let list = document.getElementById("list");

            //calculates MPH into MPM(miles per minute)
            trainAMPM = (trainAMPH / 60);
            trainBMPM = (trainBMPH / 60);
            let trainADistance = 0;
            let text = "";
            let i = 0;
            let li = "";
            
            // do that increments the minutes and Train A/Train B's current position 
            d do{
            text += "Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2);
            i++;
            trainADistance += parseFloat(trainAMPM);
            trainBDistance -= parseFloat(trainBMPM);
            li = document.createElement("li");
                
        }
        // while loop tht continues while Train A distance is less than Train B distance
        while(trainADistance < trainBDistance)

                //adds "text" variable listed in do while loop to list 
                li.innerHTML = text;
                list.appendChild(li);
            
            
            // documents the amount of minutes to the "results" div
            document.getElementById("results").innerHTML = "The two trains met after " + i + "minutes.";
            }
    

    </script>
<body>
<form id="myForm">

        <label>Train A's Speed</label>
        <input id="trainAMPH" type="number" value="" placeholder="MPH">

        <label>Train B's Speed</label>
        <input id="trainBMPH" type="number" value="" placeholder="MPH" >

        <label>Distance between Eastford and Westford</label>
        <input id="distanceApart" type="number" value=""placeholder="Miles">

        <input  type ="button" value="Submit Values" onclick="calculateTrains()">

        <ul id = "list"></ul> 

        <div id="results"></div>


    </form>
</body>

Upvotes: 0

Views: 87

Answers (3)

Jian
Jian

Reputation: 11

You may wanna change you script to as follows:

<script>
            function calculateTrains(){
                let trainAMPH= document.getElementById("trainAMPH").value;
                let trainBMPH= document.getElementById("trainBMPH").value;
                let distanceApart = trainBDistance = document.getElementById("distanceApart").value;
                let list = document.getElementById("list");
                trainAMPM = (trainAMPH / 60);
                trainBMPM = (trainBMPH / 60);
                let trainADistance = 0;
                let text = "";
                let i = 0;
                do{
                    i++;
                    trainADistance+=trainAMPM
                    trainBDistance-=trainBMPM
                    let li = document.createElement('li')
                    li.textContent="Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2)
                    document.getElementById('list').appendChild(li)
                }while(trainADistance<=trainBDistance)
            }
        </script>

Upvotes: 0

user12644556
user12644556

Reputation:

the reason why trainBDistance.toFixed(2) isn't recognized as a function is because when call document.getElementById("distanceApart").value the data type is string u need to parseInt or parseFloat that value first. You condition is while(trainADistance < trainBDistance) so you need to increment trainADistance as you said.

This might help.

function calculateTrains(){

    let trainAMPH= document.getElementById("trainAMPH").value;
    let trainBMPH= document.getElementById("trainBMPH").value;
    let distanceApart = trainBDistance = parseInt( document.getElementById("distanceApart").value );
    let list = document.getElementById("list");
    
    list.innerHTML = ''; //empty the list

    //calculates MPH into MPM(miles per minute)
    trainAMPM = (trainAMPH / 60);
    trainBMPM = (trainBMPH / 60);
    let trainADistance = 0;
    let i = 0;


    // do that increments the minutes and Train A/Train B's current position 
    do{
        let text = "Minute " + i + " Train A Position: "+ trainADistance.toFixed(2) + " miles" + " Train B Position: " + trainBDistance.toFixed(2);
        

        //adds "text" variable listed in do while loop to list 
        let li = document.createElement("li");
        li.innerHTML = text;
        list.appendChild(li);


        i++;

        trainADistance += trainAMPM; //increment trainADistance by trainAMPM
        trainBDistance -= trainBMPM; //decrease trainBDistance by trainBMPM
        
    }while(trainADistance < trainBDistance)
    // while loop tht continues while Train A distance is less than Train B distance

            
        
    // documents the amount of minutes to the "results" div
    document.getElementById("results").innerHTML = "The two trains met after " + i + "minutes."; 

}

Upvotes: 1

theonly1me
theonly1me

Reputation: 1248

There were some issue with the code, I have made the necessary changes. Please go through the in-line comments that I have added in order to understand what were the mistakes and how they can be fixed.

The code is working now, please use the below snippet to run and see it's output. Do make sure to see my comments. Goodluck!

function calculateTrains() {
  let trainAMPH = +document.getElementById("trainAMPH").value;
  let trainBMPH = +document.getElementById("trainBMPH").value;
  let distanceApart, trainBDistance;
  //The input you retrieve using .value will be a string, convert it to Number using + to use toFixed
  distanceApart = trainBDistance = +document.getElementById("distanceApart")
    .value;
  let list = document.getElementById("list");

  //calculates MPH into MPM(miles per minute)
  trainAMPM = trainAMPH / 60;
  trainBMPM = trainBMPH / 60;
  let trainADistance = 0;
  let i = 1;
  let text = "";

  // do that increments the minutes and Train A/Train B's current position
  do {
      //don't use text+=, you don't want to append, you want each <li> to be on a separate line
    text =
      "Minute " +
      i +
      " Train A Position: " +
      trainADistance.toFixed(2) +
      " miles" +
      "Train B Position: " +
      trainBDistance.toFixed(2);
    
    //create list item using template literals
    let li = `<li>${text}</li>`;
    //use insertAdjaventHTML( ) function to append the above created literal to list <ul>
    list.insertAdjacentHTML("beforeend", li);
    //increment i
    i++;
    //do the train A and train B distance calculations
    //without these calculations, your while exit condition from below will never be met, 
    //making it an infinite while loop
    trainADistance += trainAMPM;
    trainBDistance -= trainBMPM;
  } while (
    // while loop tht continues while Train A distance is less than Train B distance
    trainADistance < trainBDistance
  );

  //don't use innerHTML to append text, innerHTML is to append HTML string like '<div> hello <div>' 
  //instead use textContent or innerText properties
  document.getElementById("results").textContent =
    "The two trains met after " + i + "minutes.";
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <body>
      <form id="myForm">
        <label>Train A's Speed</label>
        <input id="trainAMPH" type="number" value="" placeholder="MPH" />
        <label>Train B's Speed</label>
        <input id="trainBMPH" type="number" value="" placeholder="MPH" />
        <label>Distance between Eastford and Westford</label>
        <input id="distanceApart" type="number" value="" placeholder="Miles" />
        <input
          type="button"
          value="Submit Values"
          onclick="calculateTrains()"
        />
        <ul id="list"></ul>
        <div id="results"></div>
      </form>
    </body>
    <script src="script.js"></script>
  </body>
</html>

Upvotes: 1

Related Questions