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

Prevent the SVG mouseclick event with CSS styling

Is it possible to prevent clicking on an SVG element using CSS? .disabled{ pointer-events: none; } After selecting the SVG element with $(".dasvg"), the console confirms the selection: [ <svg width=​"500" height=​"500" class=​"dasvg">​ ...

The curious behavior of $viewContentLoaded in Angular

For my jQuery code, I wanted it to run immediately after the template view was loaded and the DOM was modified. To achieve this, I initially used the $viewContentLoaded event in my controller. $scope.$on('$viewContentLoaded', function(){ // ...

Transform a PDF document into a Google Doc utilizing the capabilities of the Google Drive API version 3

I successfully uploaded a PDF file to Google Drive using a node server. However, I am struggling to find a way to convert it to a Google Doc format so that it can be downloaded later as a DOCX document. Here is the code snippet I've been working with ...

Execute a Bash script using Node.js based on a request from the client

I'm trying to find a way to execute a server-side script when a user clicks a button in the browser... After doing some research, I still can't seem to figure it out. Here's what we have: A Node.js server running on Fedora Red Hat (on lo ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...

Limiting the use of CSS selectors to a single class without the need to include the class name multiple

I am trying to find a solution to avoid repeating the same class name multiple times in CSS. For instance, if I have: .class1 div { color: red } .class1 h2 { color: blue } .class1 p { color: yellow } Is there a way to consolidate these three rules under ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of Boolean(new Boolean(...)) === true, it is because new Boolean(...) is treated as an object. However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN. Wh ...

How can you determine if a mouseover event is triggered by a touch on a touchscreen device?

Touchscreen touches on modern browsers trigger mouseover events, sometimes causing unwanted behavior when touch and mouse actions are meant to be separate. Is there a way to differentiate between a "real" mouseover event from a moving cursor and one trigg ...

Using DefaultSeo does not override NextSeo in every component

I am looking to dynamically change the Head tag using next-seo. While browser validation will show NEXTSeo for individual pages, Twitter, Firebase's card validation tool, and others will default to next-seo-config.js. Does anyone have a solution? S ...

Although responseText functions properly, responseXML remains constantly null

I've searched through all available answers here and still can't find a solution. I'm confident that I haven't overlooked anything obvious. My issue involves loading map markers based on latitude and longitude coordinates. The problem ...

Responsive Bootstrap 5 table - occupies full width on mobile devices, adjusts automatically on desktop screens

Is there a way to create a table that is full width on mobile using pure bootstrap classes, but only auto width on desktop? I attempted to achieve this with the following code: <table class="table table-bordered w-md-auto w-100 text-start mb-2&quo ...

AmCharts Axis renderer mistakenly renders an additional grid line

I have successfully created a basic XYChart using amcharts4. To get rid of the grid lines on the x-axis, I changed the stroke opacity for the x-axis grid to 0 using the following code: xAxis.renderer.grid.template.strokeOpacity = 0; Everything was workin ...

React app experiencing issues with onClick button methods not functioning as expected

Here is the React code for a sample homepage. My intention was to have the function run and update the page when the buttons are clicked. However, instead of updating the page, it keeps showing alerts. I have confirmed that the fetch function is pulling da ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

Styling Overflow in Coda Slider using CSS

Currently utilizing the Coda Slider for my project. For those unfamiliar with the Coda Slider, it initially hides the overflow-x position until a tab is clicked. This triggers an animation that slides the hidden DIV in either from the right or left side. ...

When attempting to render mathML in a canvas on Safari, the image load callback does not properly trigger, resulting in

I am currently working on rendering mathML into an HTML5 canvas. One suggestion I received was to embed the mathML as an SVG foreign object, render it into an image, and then display the image within the canvas. However, this method works fine in Firefox ...

Obtain the ID of element 1 by clicking on element 2 using JQuery

In the world of javascript/jquery, When button1 is clicked, we can get its id like this: var button1id = $(this).attr("id"); If button2 is clicked, how do we retrieve button1's id? This brings us to the question: How does button2 access the i ...

The controller and node js request associated are invisible to my HTML page

Here is my HTML code. I have just created a unique controller for a specific part of the code. <div class="mdl-grid" ng-controller="ValueController"> <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col"> <div class ...

What is the method for adding a before pseudo-element to my button element?

HTML & CSS Issue <button>Get Postion</button> Below is the CSS code for styling a button: button { padding: 1rem; background-color: red; color: wheat; border: 4px solid yellowgreen; position: relative; cursor: pointer; ...