Skip to content Skip to sidebar Skip to footer

Comparing 2 Times With Jquery

Thanks in advance for any help... I'm trying to (1) generate a begin time and end time for a form, (2) find the difference between the two, and (3) add the difference to a new inpu

Solution 1:

You need to parseInt() the times back out, otherwise they're just strings (as returned by .val()).

$("#totaltime").focus(function () {
    var begintime = parseInt($("#starttimeinput").val(), 10),
        endtime = parseInt($("#endtimeinput").val(), 10),
        totaltime = endtime - begintime;
    $("#totaltime").val(totaltime); 
 });

Personally, I'd sooner just store the begintime and endtime values myself, rather than in text inputs (why does the user need to see them, anyway?). Like this:

var begintime,
    endtime;
$("#starttime").click(function (event) {
     begintime = event.timeStamp;
     //$("#starttimeinput").val(begintime);
});

$("#endtime").click(function (event) {
     endtime = event.timeStamp;
     //$("#endtimeinput").val(endtime);
});

$("#totaltime").focus(function () {
    $("#totaltime").val(endtime - begintime); 
});

On a side note, I would recommend moving your jQuery code out of inline <script> tags and into an external JS file. This makes for more maintainable markup and JS. Just wrap all of your JS code in a document ready handler:

$(document).ready(function () {
    /* your code here */
});

or, more concisely,

$(function () {
    /* your code here */
});

Post a Comment for "Comparing 2 Times With Jquery"