Add jQuery hours in real time

Asked

Viewed 1,489 times

1

Hi, I’m 3 input who receive hours and minutes of a timepicker :

<input type="text" id="seg1" onBlur="calcular">
<input type="text" id="seg2" onBlur="calcular">
<input type="text" id="seg">

The first receives (08:30), the second receives (10:30) and the third returns (02:00).

I use the function below for full numbers in real time:

function calcular(){
    var segent = parseInt(document.getElementById('segent').value, 10);
    var segsai = parseInt(document.getElementById('segsai').value, 10);
    document.getElementById('resultseg').value = segent - segsai;
} 

However I am not able to make a small (nor large) code that works to return the value (02:00) in hours and minutes in real time.

3 answers

4


You gotta do more than parseInt for hh:mm have to be transformed into minutes, so the hours part has to be multiplied by 60 minutes, etc.

Suggestion:

function hmToMins(str) {
  const [hh, mm] = str.split(':').map(nr => Number(nr) || 0);
  return hh * 60 + mm;
}

function calcular() {
  const segent = hmToMins(document.getElementById('segent').value);
  const segsai = hmToMins(document.getElementById('segsai').value);
  const diff = segsai - segent;
  if (isNaN(diff)) return;
  const hhmm = [
      Math.floor(diff / 60), 
      Math.round(diff % 60)
  ].map(nr => `00${nr}`.slice(-2)).join(':');
  
  document.getElementById('resultseg').value = hhmm;
}

calcular(); // só para o exemplo mostrar mais rápido
<input type="text" id="segent" oninput="calcular()" value="08:30">
<input type="text" id="segsai" oninput="calcular()" value="10:30">
<input type="text" id="resultseg">

  • how to avoid an:an at the time of filling in the fields?

  • @Thiagokoller I edited to contemplate this case.

  • I thought I could handle the rest myself.. the deal is that I have 4 input, I need it to calculate the first two if 3 and 4 are not filled in, if they are all (seg2 - seg1) + (seg4 - seg3).. Voce can answer here or I need to open another question?

  • @Thiagokoller how does HTML and Javascript look in this case? Put a jsFiddle here for example or join the question

0

An alternative to @Sergio’s response using a little jQuery:

function calcular(){
	var c1 = $("#seg1").val().split(':').map(Number);
	var c2 = $("#seg2").val().split(':').map(Number);
	var dif = (c2[0]*60+c2[1])-(c1[0]*60+c1[1]);
	var MM = dif%60;MM.toString().length==1?MM="0"+MM:0;
	if(isNaN(dif)) return;
	var resultado = Math.floor((dif)/60) +":"+ MM;
	$("#seg").val(resultado);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="seg1" oninput="calcular()" value="08:30" />
<input type="text" id="seg2" oninput="calcular()" value="10:30" />
<input type="text" id="seg" />

0

Function to perform the calculation

var calc_times = {
    sign: ''
    , value: []
    , convert: function(  data ){
        var c = String( data ).split(':').map(Number);
        var r = 0;
        if( c[0] == undefined ){
            c[0] = 0;
        }
        r += ( Math.abs(c[0]) * 60 * 60 ) ;
        if( c[1] == undefined ){
            c[1] = 0;
        }
        r += ( Math.abs(c[1]) * 60 ) ;
        if( c[2] == undefined ){
            c[2] = 0;
        }
        r += Math.abs(c[2]) ;
        if( String( data ).indexOf("-") == 0 ){
            r = r * ( -1 ) ;
        }
        calc_times.value.push( r );
    }
    , calc: function(){
        var sec = 0 ;
        calc_times.value.forEach(function(i,o){
            sec += i ;
        })
        if( sec < 0 ){
            calc_times.sign = "-" ;
        }
        return calc_times.sign + [
            Math.abs(sec) / 60 / 60, // horas
            (Math.abs(sec) / 60) % 60, // minutos
            Math.abs(sec) % 60 // segundos
        ].map(Math.floor).map(
            s => (s < 10) ? '0' + s : s
        ).join(':');
    }
};

informs the values it wishes to calculate

calc_times.convert('-00:09:01');
calc_times.convert('00:00:03');
calc_times.convert('-00:00:01');

Callback

calc_times.calc();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.