You are viewing limited content. For full access, please sign in.

Discussion

Discussion

How to enforce time format in fields and use it for calculations?

posted on April 6, 2015 • Show version history

Hi Everyone,

I had originally posted this as a question, but I was able to resolve it myself. I'll leave it here in case someone finds it useful. 

We're using a form to work as timesheet. We're using Single Line fields for users to type in time in HH:MM (24 hour) format. Additionally, we're also tracking lunch time, which will be used in minutes. To enforce field format, we're using regular expressions:

  • Time In/Out: ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
  • Lunch: [0-9]+

 

The form looks like this:

 

Code used for calculation is:

$(document).ready(function () {
    $('.cf-table-block').on('blur', 'input', SumHours);
    function SumHours() {
        var sum = 0;
        $('.cf-table-block tbody tr').each(function () {
          var s = 0;
          var t=0, h=0, m=0;
            $(this).find('.TimeIN input').each(function () {
              t=$(this).val().split(':');
              h=parseInt(t[0], 10);
              m=parseInt(t[1], 10);
              s -= parseNumber(h+(m/60));
            });
            $(this).find('.TimeOUT input').each(function () {
              t=$(this).val().split(':');
              h=parseInt(t[0], 10);
              m=parseInt(t[1], 10);
              s += parseNumber(h+(m/60));
            });
            $(this).find('.Lunch input').each(function () {
                s -= parseNumber($(this).val()/60);
              
            });
            $(this).find('.TotalHours input').val(s);
            sum += s;
        });
        
    }
    function parseNumber(n) {
        var f = parseFloat(n); //Convert to float number.
        return isNaN(f) ? 0 : f; //treat invalid input as 0;
    }  
  
})
3 0
replied on July 6, 2016


Ditto on Duncan's comment, thanks for that Edgar.  Not being familiar with using script I didn't realise I also needed to put the string into the CSS class fields, but once I clicked to that everything started working.

Cheers,

Mike

1 0
replied on September 22, 2015

Thanks for this Edgar; exactly what I was looking for and saved me a lot of time!

Cheers,

Duncan

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.