Foros del Web » Programando para Internet » Javascript »

Suma de dos horas en java script

Estas en el tema de Suma de dos horas en java script en el foro de Javascript en Foros del Web. Hola este casi si que me ha sacado canas: tengo tres inpud text uno de HORA1 ( 01:20:00) otro de HORA2 ( 02:25:10) y otro ...
  #1 (permalink)  
Antiguo 21/05/2008, 14:37
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Suma de dos horas en java script

Hola este casi si que me ha sacado canas:

tengo tres inpud text uno de HORA1 ( 01:20:00) otro de HORA2 ( 02:25:10)

y otro de TOTAL MINUTOS ( la suma de las dos horas);


como puedo hacer que el inpud text TOTAL MINUTOS sume las horas sin tener que recargar la pantalla, es decir que amedida de que ponga una hora en los text, en el TOTAL MINUTOS apresta el total de ambas horas

gracias
  #2 (permalink)  
Antiguo 21/05/2008, 15:50
 
Fecha de Ingreso: mayo-2008
Mensajes: 43
Antigüedad: 16 años
Puntos: 0
Respuesta: Suma de dos horas en java script

haces una funcion que se active con el evento onchange. no se si a eso te referis
el onchange tiene como propiedad activarse cuadno exista un cambio a donde este referenciado el evento.
salu2
  #3 (permalink)  
Antiguo 21/05/2008, 16:01
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

oye en el caso de este codigo: como hago para que


resta se active sin recargar el navegador???

<html>
<head>
<script language="JavaScript">

function padNmb(nStr, nLen){
var sRes = String(nStr);
var sCeros = "0000000000";
return sCeros.substr(0, nLen - sRes.length) + sRes;
}

function stringToSeconds(tiempo){
var sep1 = tiempo.indexOf(":");
var sep2 = tiempo.lastIndexOf(":");
var hor = tiempo.substr(0, sep1);
var min = tiempo.substr(sep1 + 1, sep2 - sep1 - 1);
var sec = tiempo.substr(sep2 + 1);
return (Number(sec) + (Number(min) * 60) + (Number(hor) * 3600));
}

function secondsToTime(secs){
var hor = Math.floor(secs / 3600);
var min = Math.floor((secs - (hor * 3600)) / 60);
var sec = secs - (hor * 3600) - (min * 60);
return padNmb(hor, 2) + ":" + padNmb(min, 2) + ":" + padNmb(sec, 2);
}

function substractTimes(t1, t2){
var secs1 = stringToSeconds(t1);
var secs2 = stringToSeconds(t2);
var secsDif = secs1 - secs2;
return secondsToTime(secsDif);
}

function calcT3(){
with (document.frm)
t3.value = substractTimes(t1.value, t2.value);
}

</script>
</head>
<body>
<form name="frm">
Hora1 (hh:mm:ss): <input type="text" name="t1" value="12:30:15"><br>
Hora2 (hh:mm:ss): <input type="text" name="t2" value="3:40:18"><br>
<hr>
Resta (hh:mm:ss): <input type="text" name="t3" value=""><br><br>
<input type="button" onclick="calcT3()" value="Restar">
</form>
</body>
</html>


gracias
  #4 (permalink)  
Antiguo 21/05/2008, 22:23
 
Fecha de Ingreso: mayo-2008
Mensajes: 43
Antigüedad: 16 años
Puntos: 0
Respuesta: Suma de dos horas en java script

proba poniendo dentro del tag form lo siguiente on submit="return false".
  #5 (permalink)  
Antiguo 22/05/2008, 08:49
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

Cita:
Iniciado por guzmange Ver Mensaje
proba poniendo dentro del tag form lo siguiente on submit="return false".
No oye si podes aceme elfavor de reestructurar el codigo es que soy novato en el tema
  #6 (permalink)  
Antiguo 22/05/2008, 09:48
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

Muy elaborado tu script, nes. Pero Javascript maneja muy bien las fechas, así que podemos pedirle (si las horas a sumar suman menos de 24) que haga el trabajo sucio por nosotros así:

Código:
<html>
<head>
<title>Untitled</title>
</head>

<body>
<script>
function calcular(f){
horas1=f['hora1'].value.split(":");
horas2=f['hora2'].value.split(":");
horatotale=new Array();
for(a=0;a<3;a++){
horas1[a]=(isNaN(parseInt(horas1[a])))?0:parseInt(horas1[a])
horas2[a]=(isNaN(parseInt(horas2[a])))?0:parseInt(horas2[a])
horatotale[a]=(horas1[a]+horas2[a]);
}
horatotal=new Date()
horatotal.setHours(horatotale[0]);
horatotal.setMinutes(horatotale[1]);
horatotal.setSeconds(horatotale[2]);

f['horatotal'].value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}
</script>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1"  onblur="calcular(this.form)" /> + <input type="text" name="hora2" onblur="calcular(this.form)" /> = <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
</form>
</body>
</html>
Espero que también sirva!
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #7 (permalink)  
Antiguo 22/05/2008, 10:59
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

oye es que lo que quiero evitar es justamente que tengan que apretar el Submit para saber el resultado, quisiera que fuera en tiempo real amedida que escriven el valor de las horas:

este es mi codigo


<html>
<head>
<script language="JavaScript">

function padNmb(nStr, nLen){
var sRes = String(nStr);
var sCeros = "0000000000";
return sCeros.substr(0, nLen - sRes.length) + sRes;
}

function stringToSeconds(tiempo){
var sep1 = tiempo.indexOf(":");
var sep2 = tiempo.lastIndexOf(":");
var hor = tiempo.substr(0, sep1);
var min = tiempo.substr(sep1 + 1, sep2 - sep1 - 1);
var sec = tiempo.substr(sep2 + 1);
return (Number(sec) + (Number(min) * 60) + (Number(hor) * 3600));
}

function secondsToTime(secs){
var hor = Math.floor(secs / 3600);
var min = Math.floor((secs - (hor * 3600)) / 60);
var sec = secs - (hor * 3600) - (min * 60);
return padNmb(hor, 2) + ":" + padNmb(min, 2) + ":" + padNmb(sec, 2);
}

function substractTimes(t1, t2){
var secs1 = stringToSeconds(t1);
var secs2 = stringToSeconds(t2);
var secsDif = secs1 - secs2;
return secondsToTime(secsDif);
}

function calcT3(){
with (document.frm)
t3.value = substractTimes(t1.value, t2.value);
}

</script>
</head>
<body>
<form name="frm">
Hora1 (hh:mm:ss): <input type="text" name="t1" value="12:30:15"><br>
Hora2 (hh:mm:ss): <input type="text" name="t2" value="3:40:18"><br>
<hr>
Resta (hh:mm:ss): <input type="text" name="t3" value=""><br><br>
<input type="button" onclick="calcT3()" value="Restar">
</form>
</body>
</html>

gracias
  #8 (permalink)  
Antiguo 22/05/2008, 11:00
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

Sólo te pido una cosa: Prueba mi código antes de juzgarlo.
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #9 (permalink)  
Antiguo 22/05/2008, 11:51
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

Cita:
Iniciado por KarlanKas Ver Mensaje
Sólo te pido una cosa: Prueba mi código antes de juzgarlo.
oye que pena tu codigo esta teso( es decir bien), disculpame, hay alguna posibilidad de que lo publiques pero a manera de resta, es decir el mismo pero en vez de sumar pues que reste.

gracias
  #10 (permalink)  
Antiguo 22/05/2008, 14:12
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

No pasa nada! Es que me da rabia cuando me intereso en ayudar y desdeñan mi ayuda sin nisiquiera probarlo.

Para que reste sólo tienes que hacer lo siguiente:

Código PHP:
<html>
<
head>
<
title>Untitled</title>
</
head>

<
body>
<
script>
function 
calcular(f){
horas1=f['hora1'].value.split(":");
horas2=f['hora2'].value.split(":");
horatotale=new Array();
for(
a=0;a<3;a++){
horas1[a]=(isNaN(parseInt(horas1[a])))?0:parseInt(horas1[a])
horas2[a]=(isNaN(parseInt(horas2[a])))?0:parseInt(horas2[a])
horatotale[a]=(horas1[a]-horas2[a]); // Suma o resta según prefieras
}
horatotal=new Date()
horatotal.setHours(horatotale[0]);
horatotal.setMinutes(horatotale[1]);
horatotal.setSeconds(horatotale[2]);

f['horatotal'].value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}
</script>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1"  onblur="calcular(this.form)" /> - <input type="text" name="hora2" onblur="calcular(this.form)" /> = <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
</form>
</body>
</html> 
Pero no puede dar resultado negativo... espero que te sirva
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #11 (permalink)  
Antiguo 26/05/2008, 12:52
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

oye tu script esta re bueno, hast a lo estoy usando, de verdad esta bien, pero comentame algo...

lo que pasa es que tengo en mi web algo como esto:

TIEMPO ENTRADA TIEMPO SALIDA TOTAL
L1 ( cajon1) ( cajon1) (total 1)
L2( cajon2) ( cajon2) (total 2)
L3( cajon3 ) ( cajon3) (total 3)


como puedo adecuar tu script para que me funcione en la cantidad de 8 combinaciones desde L1 hasta L8.

COMENTO: en un principio opte por copiar 8 vese s la funcion y simplemente pues renombrer el nombre de cada funvion (funcion 1, funcion 2...) y porteriormente adaptar funcion`por funcion a cada cajon de texto, pero me salia error.
  #12 (permalink)  
Antiguo 26/05/2008, 13:24
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script


Te he adaptado la función para lo que quieres. Ahora ten en cuenta que en las llamadas a la función debes poner siempre:

calcular(this,'name_del_otro_campo'_a_sumar,'name_ del_campo_que_mostrará_el_resultadohoratotal')"

Fíjate que salvo el this, todos los argumentos tienen comillas simples.

En el ejemplo que teníamos sería:

calcular(this,'hora2','horatotal')"

Y ya está!
Código:
<html>
<head>
<title>Untitled</title>
<script>

function calcular(campo1,campo2,destino){
f=campo1.form;
campos=new Array(campo1.name,campo2);
horatotale=new Array(0,0,0);
for(b=0;b<campos.length;b++){
horas=f[campos[b]].value.split(":");
for(a=0;a<3;a++){
horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
horatotale[a]+=horas[a]; // Suma o resta según prefieras
}
}
horatotal=new Date()
horatotal.setHours(horatotale[0]);
horatotal.setMinutes(horatotale[1]);
horatotal.setSeconds(horatotale[2]);

f[destino].value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}
</script>
</head>

<body>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1"  onblur="calcular(this,'hora2','horatotal')" /> - 
<input type="text" name="hora2" onblur="calcular(this,'hora1','horatotal')" /> 
= <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe"  onblur="calcular(this,'juan','horatotal2')" /> - 
<input type="text" name="juan" onblur="calcular(this,'pepe','horatotal2')" /> 
= <input type="text" name="horatotal2" /> <input type="submit" value="calcular" />


</form>


</body>
</html>
Espero que así te sirva.

Un saludo!
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #13 (permalink)  
Antiguo 10/06/2008, 13:50
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

Cita:
Iniciado por KarlanKas Ver Mensaje

Te he adaptado la función para lo que quieres. Ahora ten en cuenta que en las llamadas a la función debes poner siempre:

calcular(this,'name_del_otro_campo'_a_sumar,'name_ del_campo_que_mostrará_el_resultadohoratotal')"

Fíjate que salvo el this, todos los argumentos tienen comillas simples.

En el ejemplo que teníamos sería:

calcular(this,'hora2','horatotal')"

Y ya está!
Código:
<html>
<head>
<title>Untitled</title>
<script>

function calcular(campo1,campo2,destino){
f=campo1.form;
campos=new Array(campo1.name,campo2);
horatotale=new Array(0,0,0);
for(b=0;b<campos.length;b++){
horas=f[campos[b]].value.split(":");
for(a=0;a<3;a++){
horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
horatotale[a]+=horas[a]; // Suma o resta según prefieras
}
}
horatotal=new Date()
horatotal.setHours(horatotale[0]);
horatotal.setMinutes(horatotale[1]);
horatotal.setSeconds(horatotale[2]);

f[destino].value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}
</script>
</head>

<body>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1"  onblur="calcular(this,'hora2','horatotal')" /> - 
<input type="text" name="hora2" onblur="calcular(this,'hora1','horatotal')" /> 
= <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe"  onblur="calcular(this,'juan','horatotal2')" /> - 
<input type="text" name="juan" onblur="calcular(this,'pepe','horatotal2')" /> 
= <input type="text" name="horatotal2" /> <input type="submit" value="calcular" />


</form>


</body>
</html>
Espero que así te sirva.

Un saludo!

oye gracias, pero como puedo hacer para que reste dos horas??
  #14 (permalink)  
Antiguo 10/06/2008, 15:33
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

Aprenderías mucho más si hicieras pruebas.

Cambia esto:

horatotale[a]+=horas[a]; // Suma o resta según prefieras

Por esto:

horatotale[a]-=horas[a]; // Suma o resta según prefieras

__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #15 (permalink)  
Antiguo 10/06/2008, 15:41
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

Cita:
Iniciado por KarlanKas Ver Mensaje
Aprenderías mucho más si hicieras pruebas.

Cambia esto:

horatotale[a]+=horas[a]; // Suma o resta según prefieras

Por esto:

horatotale[a]-=horas[a]; // Suma o resta según prefieras



Me la he pasado todo el dia haciendo pruevas

hasta ya hice lo que me dices hay pero nada... sera cosa del navegador???

de verdad llevo resto y nada que funciona, acason han cambiado el codigo???

Última edición por nes24; 10/06/2008 a las 15:47
  #16 (permalink)  
Antiguo 11/06/2008, 05:01
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

Había un fallo. Perdona por el rapapolvo!

A ver si ahora va!
Código:
<html>
<head>
<title>Untitled</title>
<script>

function calcular(esto,campo2,destino){
	f=esto.form;
	campos=new Array(esto.name,campo2);
	horatotale=new Array(0,0,0);
	for(b=0;b<campos.length;b++){
		horas=f[campos[b]].value.split(":");
		for(a=0;a<3;a++){
			horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
			horatotale[a]=(b==0)?horas[a]:horatotale[a]-horas[a]; // Suma o resta según prefieras
		}
	}

	horatotal=new Date()
	horatotal.setHours(horatotale[0]);
	horatotal.setMinutes(horatotale[1]);
	horatotal.setSeconds(horatotale[2]);

	f[destino].value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}
</script>
</head>

<body>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1"  onblur="calcular(this,'hora2','horatotal')" /> - 
<input type="text" name="hora2" onblur="calcular('hora1',this,'horatotal')" /> 
= <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe"  onblur="calcular(this,'juan','horatotal2')" /> - 
<input type="text" name="juan" onblur="calcular('pepe',this,'horatotal2')" /> 
= <input type="text" name="horatotal2" /> <input type="submit" value="calcular" />


</form>


</body>
</html>
Un saludo!
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.

Última edición por KarlanKas; 11/06/2008 a las 05:03 Razón: Había un pequeño fallo...
  #17 (permalink)  
Antiguo 11/06/2008, 08:43
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

Cita:
Iniciado por KarlanKas Ver Mensaje
Había un fallo. Perdona por el rapapolvo!

A ver si ahora va!
Código:
<html>
<head>
<title>Untitled</title>
<script>

function calcular(esto,campo2,destino){
	f=esto.form;
	campos=new Array(esto.name,campo2);
	horatotale=new Array(0,0,0);
	for(b=0;b<campos.length;b++){
		horas=f[campos[b]].value.split(":");
		for(a=0;a<3;a++){
			horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
			horatotale[a]=(b==0)?horas[a]:horatotale[a]-horas[a]; // Suma o resta según prefieras
		}
	}

	horatotal=new Date()
	horatotal.setHours(horatotale[0]);
	horatotal.setMinutes(horatotale[1]);
	horatotal.setSeconds(horatotale[2]);

	f[destino].value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}
</script>
</head>

<body>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1"  onblur="calcular(this,'hora2','horatotal')" /> - 
<input type="text" name="hora2" onblur="calcular('hora1',this,'horatotal')" /> 
= <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe"  onblur="calcular(this,'juan','horatotal2')" /> - 
<input type="text" name="juan" onblur="calcular('pepe',this,'horatotal2')" /> 
= <input type="text" name="horatotal2" /> <input type="submit" value="calcular" />


</form>


</body>
</html>
Un saludo!
Oye gracias, este cript funciona muy bien, salvo que en Internet explored 7 me arroja un error que dice:

linea:11
Caracter 3
Error: 'f' es nulo o no es un objeto
codigo:0
direccion...............

Cuando compruevo el script la resta tarda un tanto, es decir devo poner el cursor en distintos lados para que esta se efectue.

Te pediria el favor vefiricaras, para pder recomendar el script a mas usuarios, gracias!!!!!!!!!!!!!!!!!!!
  #18 (permalink)  
Antiguo 11/06/2008, 08:47
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

El anterior fallaba. Así ya sí que no falla.
Código:
<html>
<head>
<title>Untitled</title>
<script>


function calcular(){

	horatotale=new Array(0,0,0);
	for(b=0;b<arguments.length-1;b++){
		horas=obj(arguments[b]).value.split(":");

		for(a=0;a<3;a++){
			horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
			horatotale[a]=(b==0)?horas[a]:horatotale[a]-horas[a]; // Suma o resta según prefieras

		}
	}

	horatotal=new Date()
	horatotal.setHours(horatotale[0]);
	horatotal.setMinutes(horatotale[1]);
	horatotal.setSeconds(horatotale[2]);

	obj(arguments[2]).value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}

function obj(x){
y= document.getElementById(x);
return y;
}
</script>
</head>

<body>
<form action="#" onsubmit="calcular(this);return false">
<input type="text" name="hora1" id="hora1" onblur="calcular('hora1','hora2','horatotal')" /> - 
<input type="text" name="hora2" id="hora2" onblur="calcular('hora1','hora2','horatotal')" /> 
= <input type="text" name="horatotal" id="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe" id="pepe" onblur="calcular('pepe','juan','horatotal2')" /> - 
<input type="text" name="juan" id="juan" onblur="calcular('pepe',juan,'horatotal2')" /> 
= <input type="text" name="horatotal2" id="horatotal2" /> <input type="submit" value="calcular" />


</form>


</body>
</html>
Ahora puedes sumar (o restar) todos los campos que quieras siempre que pongas como último argumento el id del campo en el que quieras que aparezca el resultado. Es decir, puedes poner calcular("campo1","campo2","campo3","campo4",...," camporesultado").

Un saludo!
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #19 (permalink)  
Antiguo 11/06/2008, 08:50
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

Si quieres no tener que usar id en los campos de los formularios puedes cambiar la function obj para que sea así:

function obj(x){
y= document.getElementsByName(x);
return y[0];
}

Un saludo!
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #20 (permalink)  
Antiguo 11/06/2008, 11:39
Avatar de nes24  
Fecha de Ingreso: julio-2005
Mensajes: 746
Antigüedad: 18 años, 9 meses
Puntos: 3
Respuesta: Suma de dos horas en java script

oye muchicimas gracias, el script ha salido a la parfeccion, lo que loqgre hacer fue varias RASTAS:

1 hora1 ( - ) hora1.1 ( = ) total1
2 hora2 ( - ) hora2.1 ( = ) total2
3....................
4....................
5....................
6....................
7....................
8 hora8 ( - ) hora8.1 ( = ) total8

Ahora solo me queda SUMAR los totales. Como bien mencionaste en el pasado post, hay que hacer algo similar a esto, :

como calcular() RESTA pues lo clone salvo que puse:

carcular() // resta horas

sumar() // suma horas cambien ( - ) por ( + )


Calcularsuma('horatotal','horatotal2','horatotal3' ,'horatotal4','horatotal5','horatotal6','horatotal 7','horatotal8','totaltiempo')"

totaltiempo =// la SUMA de todos los totales

y el form me quedo asi:

<form name="form1" method="post" action="<? echo $PHP_SELF;?>" onsubmit="calcular(this);return false; calcularsuma(this);return false">

La cuestion es que el formulario me funciona a medias especialmente al sumar los totales, que pudo haber sido?
  #21 (permalink)  
Antiguo 11/06/2008, 15:45
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 4 meses
Puntos: 61
Respuesta: Suma de dos horas en java script

Bueno, creo que ya lo he resuelto. Ahora antes de cada nombre de campo tienes que poner el signo de lo que quieras hacer con él: sumar o restar.

Para sumar el total he hecho una solución que igual no es muy elegante pero que funciona. Dime qué te parece:

Código:
<html>
<head>
<title>Untitled</title>
<script>


function calcular(){

	horatotale=new Array(0,0,0);
	for(b=0;b<arguments.length-1;b++){

		sumador=parseInt(arguments[b].charAt(0)+"1");
		campo=arguments[b].substring(1,arguments[b].length);
		horas=obj(campo).value.split(":");

		for(a=0;a<3;a++){
			horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
			horatotale[a]=(b==0)?(sumador*horas[a]):horatotale[a]+(sumador*horas[a]); // Suma o resta según prefieras

		}
	}

	horatotal=new Date()
	horatotal.setHours(horatotale[0]);
	horatotal.setMinutes(horatotale[1]);
	horatotal.setSeconds(horatotale[2]);

	obj(arguments[arguments.length-1]).value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}

function obj(x){
y= document.getElementsByName(x);
return y[0];
}
</script>
</head>

<body>
<form action="#" onsubmit="calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo');return false">
<input type="text" name="hora1" onblur="calcular('+hora1','-hora2','horatotal');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="hora2" onblur="calcular('+hora1','-hora2','horatotal');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe" onblur="calcular('+pepe','-juan','horatotal2');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="juan" onblur="calcular('+pepe','-juan','horatotal2');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal2" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe2" onblur="calcular('+pepe2','-juan2','horatotal3');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="juan2" onblur="calcular('+pepe2','-juan2','horatotal3');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal3" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe4" onblur="calcular('+pepe4','-juan4','horatotal4');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="juan4" onblur="calcular('+pepe4','-juan4','horatotal4');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal4" /> <input type="submit" value="calcular" />
<br />
<br />


<input type="text" name="totalisimo" />

</form>


</body>
</html>
El problema está en que si la suma de todas las horas da más de 23 horas con 59 minutos y 59 segundos no pondrá todas las horas sino las que sobrepasen esas 24 horas. ¿Importa? Sumarán alguna vez más de 24 horas?
Un saludo!
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #22 (permalink)  
Antiguo 11/06/2008, 17:19
 
Fecha de Ingreso: junio-2008
Mensajes: 8
Antigüedad: 15 años, 10 meses
Puntos: 0
Respuesta: Suma de dos horas en java script

Cita:
Probando probando
  #23 (permalink)  
Antiguo 24/02/2010, 10:32
 
Fecha de Ingreso: febrero-2010
Mensajes: 1
Antigüedad: 14 años, 2 meses
Puntos: 0
Respuesta: Suma de dos horas en java script

Cita:
Iniciado por KarlanKas Ver Mensaje
Bueno, creo que ya lo he resuelto. Ahora antes de cada nombre de campo tienes que poner el signo de lo que quieras hacer con él: sumar o restar.

Para sumar el total he hecho una solución que igual no es muy elegante pero que funciona. Dime qué te parece:

Código:
<html>
<head>
<title>Untitled</title>
<script>


function calcular(){

	horatotale=new Array(0,0,0);
	for(b=0;b<arguments.length-1;b++){

		sumador=parseInt(arguments[b].charAt(0)+"1");
		campo=arguments[b].substring(1,arguments[b].length);
		horas=obj(campo).value.split(":");

		for(a=0;a<3;a++){
			horas[a]=(isNaN(parseInt(horas[a])))?0:parseInt(horas[a])
			horatotale[a]=(b==0)?(sumador*horas[a]):horatotale[a]+(sumador*horas[a]); // Suma o resta según prefieras

		}
	}

	horatotal=new Date()
	horatotal.setHours(horatotale[0]);
	horatotal.setMinutes(horatotale[1]);
	horatotal.setSeconds(horatotale[2]);

	obj(arguments[arguments.length-1]).value=horatotal.getHours()+":"+horatotal.getMinutes()+":"+horatotal.getSeconds();

}

function obj(x){
y= document.getElementsByName(x);
return y[0];
}
</script>
</head>

<body>
<form action="#" onsubmit="calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo');return false">
<input type="text" name="hora1" onblur="calcular('+hora1','-hora2','horatotal');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="hora2" onblur="calcular('+hora1','-hora2','horatotal');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe" onblur="calcular('+pepe','-juan','horatotal2');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="juan" onblur="calcular('+pepe','-juan','horatotal2');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal2" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe2" onblur="calcular('+pepe2','-juan2','horatotal3');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="juan2" onblur="calcular('+pepe2','-juan2','horatotal3');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal3" /> <input type="submit" value="calcular" />
<br />
<br />
<input type="text" name="pepe4" onblur="calcular('+pepe4','-juan4','horatotal4');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> - 
<input type="text" name="juan4" onblur="calcular('+pepe4','-juan4','horatotal4');calcular('+horatotal','+horatotal2','+horatotal3','+horatotal4','totalisimo')" /> 
= <input type="text" name="horatotal4" /> <input type="submit" value="calcular" />
<br />
<br />


<input type="text" name="totalisimo" />

</form>


</body>
</html>
El problema está en que si la suma de todas las horas da más de 23 horas con 59 minutos y 59 segundos no pondrá todas las horas sino las que sobrepasen esas 24 horas. ¿Importa? Sumarán alguna vez más de 24 horas?
Un saludo!

Hola, he probado tu codigo pero resulta que si lo pruebo con estos valores: hora1=00:02:00 y hora2=00:09:00 no resta bien y nose porque. Si puedes ayudarme te lo agradeceria mucho
  #24 (permalink)  
Antiguo 17/09/2010, 23:38
 
Fecha de Ingreso: junio-2010
Mensajes: 73
Antigüedad: 13 años, 10 meses
Puntos: 1
Respuesta: Suma de dos horas en java script

como hago que coloque dos ceros ejemplo 3:00 - 2:00 = 1:0:0 y qisiera que mostrara 1:00:00
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 2 personas (incluyéndote)




La zona horaria es GMT -6. Ahora son las 02:20.