Foros del Web » Programando para Internet » Javascript »

[SOLUCIONADO] Ejecutar funcion al cargar página

Estas en el tema de Ejecutar funcion al cargar página en el foro de Javascript en Foros del Web. Buen dia Espero y puedan ayudarme, tengo una funcion que me da el numero de semana al presionar un boton, pero lo que necesito es ...
  #1 (permalink)  
Antiguo 11/03/2014, 15:26
 
Fecha de Ingreso: abril-2010
Mensajes: 40
Antigüedad: 14 años
Puntos: 0
Ejecutar funcion al cargar página

Buen dia

Espero y puedan ayudarme, tengo una funcion que me da el numero de semana al presionar un boton, pero lo que necesito es que al momento de cargar la página se llene automaticamente el campo "semana", osea que ejecute la funcion en automatico ya intente con el onload en body pero no me funciono...

Les dejo el codigo que tengo

De antemano muchas gracias por su apoyo

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
 <script type="text/javascript">
function getWeekNr(){
	var now=new Date(),i=0,f,sem=(new Date(now.getFullYear(), 0,1).getDay()>0)?1:0;
	while( (f=new Date(now.getFullYear(), 0, ++i)) < now ){
		if(!f.getDay()){
			sem++;
		}
	}
	return sem;
}
</script>
</head>

<body>
<input name="semana" type="text" class="tb836" id="semana" size="5" readonly="readonly" onclick="this.value=getWeekNr();" />
</body>
</html> 
  #2 (permalink)  
Antiguo 11/03/2014, 15:35
Avatar de andresgarciadev  
Fecha de Ingreso: junio-2013
Mensajes: 218
Antigüedad: 10 años, 9 meses
Puntos: 32
Respuesta: Ejecutar funcion al cargar página

llama al input por id y dale como value lo que te retorna la funcion
http://jsfiddle.net/Uw25N/
  #3 (permalink)  
Antiguo 11/03/2014, 15:56
 
Fecha de Ingreso: abril-2010
Mensajes: 40
Antigüedad: 14 años
Puntos: 0
Respuesta: Ejecutar funcion al cargar página

Gracias por contestar andresgarciadev

Soy nuevo en esto de Javascript ya intente lo que me mencionas pero no funciona

anexo mi codigo

Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
 <script type="text/javascript">
document.getElementById('semana').value=getWeekNr();
function getWeekNr(){
	var now=new Date(),i=0,f,sem=(new Date(now.getFullYear(), 0,1).getDay()>0)?1:0;
	while( (f=new Date(now.getFullYear(), 0, ++i)) < now ){
		if(!f.getDay()){
			sem++;
		}
	}
	return sem;
}
</script>
</head>

<body onload="getWeekNr();">
<input name="semana" type="text" class="tb836" id="semana" size="5" readonly="readonly" />
</body>
</html> 
  #4 (permalink)  
Antiguo 11/03/2014, 16:46
 
Fecha de Ingreso: mayo-2011
Ubicación: Zaragoza
Mensajes: 58
Antigüedad: 12 años, 11 meses
Puntos: 5
Respuesta: Ejecutar funcion al cargar página

La funcion getWeekNr() devuelve sem asi que esto onload="getWeekNr();" no tiene sentido por que no estas depositando el valor de sem en ningun lado.

La line que incluye andresgarciadev coloca el valor de sem dentro del input si, pero al usar http://jsfiddle.net no me queda del todo claro desde donde se hace la llamada a la funcion. En general, yo cargaria primero la funcion, luego el documento y al final llamaria a la funcion para cargar el valor que devuelve dentro del input (a ver si me he explicado bien):

Código HTML:
Ver original
  1. ...
  2. ...
  3. <script type="text/javascript">
  4. function getWeekNr(){
  5.     var now=new Date(),i=0,f,sem=(new Date(now.getFullYear(), 0,1).getDay()>0)?1:0;
  6.     while( (f=new Date(now.getFullYear(), 0, ++i)) < now ){
  7.         if(!f.getDay()){
  8.             sem++;
  9.         }
  10.     }
  11.     return sem;
  12. }
  13. </head>
  14. <input name="semana" type="text" class="tb836" id="semana" size="5" readonly="readonly" />
  15. document.getElementById('semana').value=getWeekNr();
  16. </body>
  17. ...

Actualizo: Si quieres puedes usar addEventListener y asi el codigo javascript puedes llevarlo fuera:

Código Javascript:
Ver original
  1. window.addEventListener('load',getWeekNr());
  2. function getWeekNr(){
  3.     var now=new Date(),i=0,f,sem=(new Date(now.getFullYear(), 0,1).getDay()>0)?1:0;
  4.     while( (f=new Date(now.getFullYear(), 0, ++i)) < now ){
  5.         if(!f.getDay()){
  6.             sem++;
  7.         }
  8.     }
  9. document.getElementById('semana').value=sem;
  10. }

Fijate que el valor de sem lo coloco dentro del input con getElementB...

Igual que el anterior este codigo tiene que estar al final, antes de cerrar body.

Saludos.

Última edición por jarios; 11/03/2014 a las 16:57
  #5 (permalink)  
Antiguo 12/03/2014, 10:19
Colaborador
 
Fecha de Ingreso: septiembre-2013
Ubicación: España
Mensajes: 3.648
Antigüedad: 10 años, 7 meses
Puntos: 578
Respuesta: Ejecutar funcion al cargar página

Código:
window.addEventListener('load',getWeekNnr);
Si no, la función se ejecuta inmediatamente...
  #6 (permalink)  
Antiguo 12/03/2014, 12:18
 
Fecha de Ingreso: abril-2010
Mensajes: 40
Antigüedad: 14 años
Puntos: 0
Respuesta: Ejecutar funcion al cargar página

Muchas gracias por sus respuestas jarios, PHPeros y andresgarciadev

me funciono justo como lo necesitaba

Dejo el codigo completo por si alguien mas lo llegara a utilizar

Código HTML:
...
<head>
...
<script type="text/javascript">
function getWeekNr(){
    var now=new Date(),i=0,f,sem=(new Date(now.getFullYear(), 0,1).getDay()>0)?1:0;
    while( (f=new Date(now.getFullYear(), 0, ++i)) < now ){
        if(!f.getDay()){
            sem++;
        }
    }
    return sem;
}
</script>
</head>
<body>
<input name="semana" type="text" class="tb836" id="semana" size="5" readonly="readonly" />
<script>
document.getElementById('semana').value=getWeekNr();
</script>
</body>
...

Etiquetas: javascript+html, numero, onload, semana
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




La zona horaria es GMT -6. Ahora son las 19:51.