Calculate the sum of hours worked in a day using pure JavaScript, no external libraries required

Hello, I'm new to this website and please excuse me if my English is not perfect, I am trying my best to communicate :)
I have been working on a page that calculates the total hours worked in a day and this is what I have achieved so far until 15/06/17. You can view it on this page.
note: The language used on my page is Italian, I apologize for any inconvenience.

giorno = day

The issue I am facing is with solving the function of the button named "Calcola". Here is the code snippet: (since I am unable to write code here, please refer to the code on "my page" using Google tools)

The problem is specifically within this section:

function differenza()  
{       
       issue...   
}

I hope this explanation has been clear, once again I apologize for my English as I am still learning.

Answer №1

@masterNixe has done it! Check out this amazing result and please Give it a try

It's a slightly different approach compared to your example, @masterNixe, but thank you :D
Here is the link to my page if you want to test it out
If anyone finds a bug, feel free to let me know

<script>
    function calculateTotalDifference() {
        var i;
        for (i = 1; i < document.getElementById("tabella").rows.length; i++) {
            differenzaRiga(i);
        }
    }

    function differenzaRiga(i) {

        var result = firstCheck(i);
        if (result == false){
            return false;
        }

        /* calculation */
        var exitMinutes = result.exitMinutes;
        var entryMinutes = result.entryMinutes;
        var breakMinutes = result.breakMinutes;

        var totalDifferenceInMin = exitMinutes - entryMinutes - breakMinutes;
        var hoursDone = Math.floor(totalDifferenceInMin / 60);
        var minutesDone = totalDifferenceInMin % 60;

        document.getElementById("Giorno" + i + "Totale").value = (pad(hoursDone) + ":" + pad(minutesDone));
    }

    function pad(n) { 
        return (n < 10) ? ("0" + n) : n;
    }
    document.getElementById('body').onkeypress = function (e) {
        if (!e) e = window.event;
        var keyCode = e.keyCode || e.which;

        if (keyCode == '13') {
            calculateTotalDifference();
        }
    }

    function firstCheck(i) {
        // logic for checking values before calculations
    }

</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for (variable or {}) to function seamlessly across all web browsers when using Javascript

When writing code in JavaScript, the if(variable) clause is used to check if a list or array is not null or undefined in order to avoid exceptions. Here's an example: if (list) for (var k in list) { ... if (array) for (var i = array.l ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Vue component failing to display data passed as props

As a Vue beginner, I ventured into creating a custom component and attempted to bind everything just like in the basic Vue CLI template. Here is my code snippet. Circle.vue <template> <div :style="custom"> </div> </template&g ...

Resetting the check status in html can be accomplished by using the checked

I am currently working on a popup feature in HTML <div id="term_flags" class="term_flags"> <div class="modal-users-content flagsContent"> <div class="modal-users-header"> <span class="close" ng-clic ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...

Display the printed outcome in a fresh window

HTML: <form id="dbview" method="post" action="core/process.php"> .... <p style='text-align:center;'> <input id='delete' type='submit' name='process' value='Delete selected'/> < ...

Instructions for integrating AJAX into a PHP script

I am looking to incorporate AJAX into my PHP file so that when I delete an item from a list, the data automatically reloads and the list is updated with the new information. I have created a list of all my data along with a delete button. Below is the PH ...

Tips for arranging divs in a row to switch to stacking when the screen size decreases

Sorry if this question seems repetitive, but as a newbie, deciphering posts from others has been overwhelming! I have two divs placed side by side within a wrapper, but I need them to stack on top of each other when viewed on a tablet or phone. Below is t ...

Is window.open exclusive to Firefox?

Apologies if this question has been asked before! I am experiencing some issues with my Javascript code. It works perfectly in Firefox and opens a pop-up window as expected. However, in IE 9 it does nothing, and in Chrome it behaves like a link and change ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

What is the process for implementing text box validation on a button click within a gridview in asp.net utilizing javascript?

How can I implement textbox blank validation on button click within a gridview using JavaScript? My gridview has multiple rows with 2 textboxes and a save button in each row. I need to validate the textboxes when their corresponding save button is clicked. ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...

Firestore information does not appear visible

I encountered an issue with my custom hook where I am fetching images from a Firestore collection. Everything was working smoothly until I attempted to retrieve the metadata of the images as well. The problem arose when I included the getMetaData function, ...

Connect the Vue component to the Vue instance

I am currently working with a Vue component that looks like this: Vue.component('number-input', { props: {}, template: `<textarea class="handsontableInput subtxt area-custom text-center text-bold" v-model="displayValue" @blur="isInput ...

Backgrounds filled by nested <li> elements inside another <li> element

My website features a sidebar menu with nested lists. When hovering over a list item, a sub-list appears. However, I am having an issue where the background color fills the entire sub-list instead of just the first list item. See the images below for clari ...

Displaying HTML content from a Vuejs response within a Dialog box

After receiving a response from the server via a REST request in HTML format, I have saved it in a data:[] variable. When I log this data on the console, it appears as raw HTML code. This reply is currently stored as a String, and my challenge now is to co ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

How do I create a new JSON Object with only two properties by selecting from an existing JSON Object with four properties?

Below is a JSON object example: [ {'car':'punto','brand':'fiat','color':'black','model':'2007'}, {'car':'XUV500','brand':&ap ...