-2

This is the function that I am using to calculate the total time:

This function adds the total of all input fields with a class called calctime. The column called block time has fields with this calctime class. I had used another function to format the output in these columns as Hours and Mins eg 1:12 but now i cannot add the total time. I can only add hours. I have been stuck on this problem for days now.

enter image description here

<script>
    function findTotal() {
        var arr = document.getElementsByClassName('calctime');
        var tot = 0;
        for (var i = 0; i < arr.length; i++) {
            if (parseFloat(arr[i].value))
                tot += parseFloat(arr[i].value);
        }
        document.getElementById('grandtotal').value = tot + ':' + "00";
    }
</script>
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • 2
    What are the typical values of the calctime elements? parseFloat("0:49") will not give you minutes – mplungjan Aug 25 '23 at 13:39
  • Does this answer your question? [How to create a function to calculate/sum hours and minutes](https://stackoverflow.com/questions/71498088/how-to-create-a-function-to-calculate-sum-hours-and-minutes) – gre_gor Aug 25 '23 at 13:42
  • `parseFloat('0:49')` will return 0 as colon is not a valid decimal character. – phuzi Aug 25 '23 at 13:53

1 Answers1

1

Your parseFloat on a 0:49 will not return hours and minutes

Here is a better script

const findTotal = () => {
  const arr = [...document.querySelectorAll('.calctime')];
  const totalMinutes = arr.reduce((acc, { value }) => {
    let [hours, minutes] = value.split(":").map(num => +num)
    hours = isNaN(hours) ? 0 : hours; // hours may be empty or not a number
    minutes = isNaN(minutes) ? 0 : minutes; // minutes may be empty or not a number
    return acc + (hours * 60) + minutes;
  }, 0);

  
  const resultHours = Math.floor(totalMinutes / 60);
  const resultMinutes = String(totalMinutes % 60).padStart(2, '0');

  document.getElementById('grandtotal').value = `${resultHours}:${resultMinutes}`;
};

document.querySelector("table tbody").addEventListener("input", findTotal)
<table>
  <tbody>
    <tr>
      <td>
        <input type="text" class="calctime" value="0:39" />
      </td>
    </tr>
    <tr>
      <td><input type="text" class="calctime" value="3:01" />
      </td>
    </tr>
  </tbody>
</table>
<input type="text" id="grandtotal" value="0:00" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236