Date and hour calculation

rafrev 12 Feb, 2016
Hi, I have a problem with the result of my calculation with my fileds.

I draw this form:

I want to calculate the ammount of hours from the two time fields and write the result in a new text field.
In the total field the result will never be greater than 24 hours total.
this is a calculator of worked hours.

The date fiels are populated from a chronoform data picker.
The hour fields are populated from list of values of hour

I write this jquery code in the Action load javascript:

jQuery(document).ready(function (op) {
  op('#data_inizio').on('change', calc);
  op('#ora_inizio').on('change', calc);
  op('#data_fine').on('change', calc);
  op('#ora_fine').on('change', calc);
  function calc() {
    var JS_data_inizio = op('#data_inizio').val();
	var JS_data_fine = op('#data_fine').val();
    var JS_ora_inizio = op('#data_inizio').val();
	var JS_ora_fine = op('#data_fine').val();
	var giorno = 24;
    if ( JS_data_fine > JS_data_inizio ){
      op('#ore_totali').val((giorno - JS_ora_inizio) + JS_ora_fine);
    else {
	  op('#ore_totali').val(JS_ora_fine - JS_ora_inizio);

This is the result:


I expected to see the result equal to 9 hours.
Where i wrong?
Can you help me?

Thanks in advance.

Bye Raffaele.
GreyHead 13 Feb, 2016
Hi Raffaele,

You can use your browser web developer tools to help debug your JavaScript. I'd guess that the problem is with this line
op('#ore_totali').val((giorno - JS_ora_inizio) + JS_ora_fine);
The + operator works in two ways - if both the operands are numbers it adds them - it either of them are strings it concatenates them into a longer string.

Please see this StackOverFlow answer for another way to do this,

This topic is locked and no more replies can be posted.