Derek Derek - 1 year ago 50
HTML Question

JS Time Tracker not working as expected

I have a timer mainly using javascript, currently the start/stop functionality works fine. When user hits "Stop" button it takes the time from the #time element, converts it to decimal value and updates the hidden #counter element. For example an 1 and a half hours would be converted to 1.50

My problem is I also want to allow users to edit the time manually so I have a little plugin that was created to do allow for this.

There are 2 problems:

  1. If a user manually adds their time by double clicking the element and adjusting then were to hit save, the #counter element has not be updated so it is submitting the time as 0.

  2. If a user were to manually set their time and then hit the Start button, the clock starts from 0 instead of the time they specified.

I have a JS Fiddle available here:

Toward the bottom of the JS block in that fiddle you will see:

//implement plugin
$('span#time').editable().on('editsubmit', function (event, val) {
console.log('text changed to ' + millisecondsToHours(val));

which I believe is the event that fires each time the user manually enters time.

Question: How can I make it where when someone manually enters time that it automatically updates the #counter field with the converted values and if they press start it starts from that time?

What I tried: I tried playing with the
function and have it currently trying to print the value to the console but I am not getting results

Answer Source

I have create an override method on your clsStopwatch class, like so:

this.override = function(time) {
        lapTime = time;

This will update the lapTime, passing in a time in milliseconds. To do this I created a new function which accepts a string:

function stringToMilliseconds(str) {
        var a = str.split(':'); // split it at the colons
        var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 
        return seconds * 1000;

This will return the number of milliseconds from the edited string in the id #time element span.

Finally, I updated the submit editable event to call the override:

$('span#time').editable().on('editsubmit', function (event, val) {

Here is the updated JSFiddle

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download