Foros del Web » Programando para Internet » Javascript »

FAQs JavaScript

Estas en el tema de FAQs JavaScript en el foro de Javascript en Foros del Web. P: ¿Como puedo saber la cantidad de días, meses y años que hay entre dos fechas? R: [ ver ejemplo ] Código PHP: < html ...

  #121 (permalink)  
Antiguo 29/04/2003, 10:42
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
123.- Resta de fechas

P: ¿Como puedo saber la cantidad de días, meses y años que hay entre dos fechas?

R: [ver ejemplo]

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
   function 
cerosIzq(sValnPos){
    var 
sRes sVal;
    for (var 
sVal.lengthnPosi++)
     
sRes "0" sRes;
    return 
sRes;
   }

   function 
armaFecha(nDianMesnAno){
    var 
sRes cerosIzq(String(nDia), 2);
    
sRes sRes "/" cerosIzq(String(nMes), 2);
    
sRes sRes "/" cerosIzq(String(nAno), 4);
    return 
sRes;
   }

   function 
sumaMes(nDianMesnAnonSum){
    if (
nSum >= 0){
     for (var 
0Math.abs(nSum); i++){
      if (
nMes == 12){
       
nMes 1;
       
nAno += 1;
      } else 
nMes += 1;
     }
    } else {
     for (var 
0Math.abs(nSum); i++){
      if (
nMes == 1){
       
nMes 12;
       
nAno -= 1;
      } else 
nMes -= 1;
     }
    }
    return 
armaFecha(nDianMesnAno);
   }

   function 
esBisiesto(nAno){
    var 
bRes true;
    
res bRes && (nAno == 0);
    
res bRes && (nAno 100 != 0);
    
res bRes || (nAno 400 == 0);
    return 
bRes;
   }

   function 
finMes(nMesnAno){
    var 
nRes 0;
    switch (
nMes){
     case 
1nRes 31; break;
     case 
2nRes 28; break;
     case 
3nRes 31; break;
     case 
4nRes 30; break;
     case 
5nRes 31; break;
     case 
6nRes 30; break;
     case 
7nRes 31; break;
     case 
8nRes 31; break;
     case 
9nRes 30; break;
     case 
10nRes 31; break;
     case 
11nRes 30; break;
     case 
12nRes 31; break;
    }
    return 
nRes + (((nMes == 2) && esBisiesto(nAno))? 10);
   }

   function 
diasDelAno(nAno){
    var 
nRes 365;
    if (
esBisiesto(nAno)) nRes++;
    return 
nRes;
   }

   function 
anosEntre(nDi0nMe0nAn0nDi1nMe1nAn1){
    var 
nRes Math.max(0nAn1 nAn0 1);
    if (
nAn1 != nAn0)
     if ((
nMe1 nMe0) || ((nMe1 == nMe0) && (nDi1 >= nDi0)))
      
nRes++;
    return 
nRes;
   }

   function 
mesesEntre(nDi0nMe0nAn0nDi1nMe1nAn1){
    var 
nRes;
    if ((
nMe1 nMe0) || ((nMe1 == nMe0) && (nDi1 nDi0))) nMe1 += 12;
    
nRes Math.max(0nMe1 nMe0 1);
    if ((
nDi1 nDi0) && (nMe1 != nMe0)) nRes++;
    return 
nRes;
   }

   function 
diasEntre(nDi0nMe0nAn0nDi1nMe1nAn1){
    var 
nRes;
    if (
nDi1 nDi0nDi1 += finMes(nMe0nAn0);
    
nRes Math.max(0nDi1 nDi0);
    return 
nRes;
   }

   function 
mayorOIgual(nDi0nMe0nAn0nDi1nMe1nAn1){
    var 
bRes false;
    
bRes bRes || (nAn1 nAn0);
    
bRes bRes || ((nAn1 == nAn0) && (nMe1 nMe0));
    
bRes bRes || ((nAn1 == nAn0) && (nMe1 == nMe0) && (nDi1 >= nDi0));
    return 
bRes;
   }

   function 
calcula(){
    var 
sFc0 document.frm.fecha0.value// Se asume válida
    
var sFc1 document.frm.fecha1.value// Se asume válida
    
var nDi0 parseInt(sFc0.substr(02), 10);
    var 
nMe0 parseInt(sFc0.substr(32), 10);
    var 
nAn0 parseInt(sFc0.substr(64), 10);
    var 
nDi1 parseInt(sFc1.substr(02), 10);
    var 
nMe1 parseInt(sFc1.substr(32), 10);
    var 
nAn1 parseInt(sFc1.substr(64), 10);
    if (
mayorOIgual(nDi0nMe0nAn0nDi1nMe1nAn1)){
     var 
nAno anosEntre(nDi0nMe0nAn0nDi1nMe1nAn1);
     var 
nMes mesesEntre(nDi0nMe0nAn0nDi1nMe1nAn1);
     var 
nDia diasEntre(nDi0nMe0nAn0nDi1nMe1nAn1);
     var 
nTtM nAno 12 nMes;
     var 
nTtD nDia;
     for (var 
nAn0nAn0 nAnoi++) nTtD += diasDelAno(nAno);
     for (var 
nMe0nMe0 nMesj++) nTtD += finMes(jnAn1);
     var 
nTSS Math.floor(nTtD 7);
     var 
nTSD nTtD 7;
     
document.frm.difDMA.value String(nAno) + " años, " String(nMes) + " meses, " String(nDia) + " días";
     
document.frm.difDM.value String(nTtM) + " meses, " String(nDia) + " días";
     
document.frm.difD.value String(nTtD) + " días";
     
document.frm.difSD.value String(nTSS) + " semanas, " String(nTSD) + " días";
    } else 
alert("Error en rango");
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td>
      <table border="1">
       <tr>
        <td align="right">
         Fecha inicial (dd/mm/aaaa)
        </td>
        <td>
         <input type="text" name="fecha0" value="31/08/1996">
        </td>
       </tr>
       <tr>
        <td align="right">
         Fecha final (dd/mm/aaaa)
        </td>
        <td>
         <input type="text" name="fecha1" value="09/07/1999">
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (D,M,A)
        </td>
        <td>
         <input type="text" name="difDMA" readonly>
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (D,M)
        </td>
        <td>
         <input type="text" name="difDM" readonly>
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (D)
        </td>
        <td>
         <input type="text" name="difD" readonly>
        </td>
       </tr>
       <tr>
        <td align="right">
         Diferencia (SD)
        </td>
        <td>
         <input type="text" name="difSD" readonly>
        </td>
       </tr>
      </table>
     </td>
    </tr>
    <tr>
     <td align="center">
      <input type="button" value="Calcular" onclick="calcula()">
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 
  #122 (permalink)  
Antiguo 29/04/2003, 10:55
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
124.- Controlar que se rellenan todos los campos

P.- ¿Cómo indicar a un visitante de un formulario que se ha dejado campos sin rellenar?
R.- Estando delante cuando lo rellene o de esta manera:
Se pueden poner todos los campos que se quiera.


Código PHP:
<html>
<
head>

    <
script>
    
//Script original de KarlanKas para Forosdelweb.com


    
function comprobar(){var mal=false;
    
numero=document.forms[0].elements.length;
    for(
a=0;a<numero;a++){
    if (
document.forms[0].elements[a].value==""){document.forms[0].elements[a].style.backgroundColor="#ffffcc";mal=true;}
    else{
document.forms[0].elements[a].style.backgroundColor="white";}
    }
    if(
mal){alert("Por favor, rellene las cajas coloreadas");}
    else{
document.forms[0].submit()}
    }
    
    
</script>
</head>

<body>
<form action="javascript:alert('enviando')"
      method="post"
      name="formulario"
      id="formulario"
      style="font:normal 10px/10px verdana;border:solid 1px black;text-align:right;width:300px;"
      >
      Nombre: <input type="text"
             name="cosa"
             id="cosa"><br>
      Apellidos: <input type="text"
             name="cosa"
             id="cosa"><br>
      Dirección: <input type="text"
             name="cosa"
             id="cosa"><br>
      Nombre del perro: <input type="text"
             name="cosa"
             id="cosa"><br>
      Pais: <input type="text"
             name="cosa"
             id="cosa"><br>
      Conocidos con perro: <input type="text"
             name="cosa"
             id="cosa"><br>
             <input onclick="comprobar()"
                     type="button"
                    name="enviar"
                    value="Enviar!">
    
      
      
      
      </form>


</body>
</html> 
__________________
Cómo escribir

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

Última edición por KarlanKas; 04/01/2005 a las 11:48
  #123 (permalink)  
Antiguo 29/04/2003, 11:11
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
125.- Contar caracteres iguales seguidos en un input

P.-Cómo saber si han rellenado un input con varios caracteres iguales?
R.-Por medio de este script:

Tema: Formularios


Código PHP:
<html>
<
head>
    <
title>Contando letritas</title>
    <
script>
//Script original de KarlanKas para Forosdelweb.com


    
record=0;
    
igual=1;
    var 
letraRecord
    
var b=0
    
var letra=""
    
function comprobar(esto){
    
    for (
a=1;a<esto.length;a++){
    
    if (
esto.charAt(a)==esto.charAt(b)){
    
igual=igual+1;
    
letra=esto.charAt(a);}
    else{
    if(
igual>record){record=igual;letraRecord=letra}
    
igual=1
    
}
    
b=a
    
}
    if(
igual>record){record=igual;letraRecord=letra}
    if (
record>1){alert("La letra que más se repite es la "+letraRecord+" que aparece seguida "+record+" veces.")}
    else {
alert("Ninguna letra se repite seguida");}
    }
    
</script>
</head>

<body>
<form action="javascript:alert('HOLAA!!')"
      method="post"
      name="formuario"
      id="formuario">
      
      <input type="text"
             name="caja"
             size="130"
             onblur="comprobar(this.value)">
      
      
      </form>


</body>
</html> 
Dernuke propone una versión usando expresiones regulares y propone algún variante:

Código:
<html>
<head>
<title>Contando letritas</title>
<script>
// por derkeNuke
function comprobar(str) {


    var res=str.match(/([a-z]){1}\1+/gi);
    
    
    mensaje="Las repeticiones de letras seguidas son: \r";
    for(a=0; a<res.length; a++)
        mensaje+="- "+res[a].substring(0,1)+" "+res[a].length+" veces.\r";
    alert(mensaje);
    
    
    // si queremos ordenar el resultado de mayor a menor repeticion:
    res.sort( function(a,b) {
        if(a.length>b.length) return -1;
        else if(a.length==b.length) return 0;
        else return 1;
    } );
    
    
    mensaje="Las repeticiones de letras seguidas ya ordenadas son: \r";
    for(a=0; a<res.length; a++)
        mensaje+="- "+res[a].substring(0,1)+" "+res[a].length+" veces.\r";
    alert(mensaje);
    
    
}
</script>
</head>

<body>
<form action="javascript:alert('HOLAA!!')"
      method="post"
      name="formuario"
      id="formuario">
       
      <input type="text"
             name="caja"
             size="130"
             value="eqewwqFaaaasscccFasaeqw"
             onblur="comprobar(this.value)">
      </form>


</body>
</html>
__________________
Cómo escribir

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

Última edición por KarlanKas; 02/08/2005 a las 07:45
  #124 (permalink)  
Antiguo 29/04/2003, 11:25
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
126.- Botones de indicación de navegación

P.- Me gustaría saber cómo puedo hacer para que además de que mis botones cambien de imagen cuando paso por encima con el ratón (de imagen A a Imagen B), también cambie a una tercera imagen diferente cuando hago ‘clic’ con el ratón sobre el botón, y que permanezca así hasta que pinche con el ratón en otra opción diferente del menú, momento en el que el enlace anteriormente abierto debe volver a la imagen A.

R.- Con este código:

Código PHP:
<html>
<
head>

    <
script>
    
//Script original de KarlanKas para forosdelweb.com
    
var imagen=new Array;
    
imagen[0]=new Image;
    
imagen[0].no=new Image();
    
imagen[0].pincha=new Image();
    
imagen[0].si=new Image();
    
    
imagen[1]=new Image;
    
imagen[1].no=new Image();
    
imagen[1].pincha=new Image();
    
imagen[1].si=new Image();

    
imagen[2]=new Image;
    
imagen[2].no=new Image();
    
imagen[2].pincha=new Image();
    
imagen[2].si=new Image();

    
imagenAnterior=new Image;
    
    var 
numeroAnterior=0
//--------- PON AQUÍ LA RUTA DE LAS IMÁGENES (NO HAN DE SER ABSOLUTAS)---------------
    
    
imagen[0].no.src="no.gif";
    
imagen[0].pincha.src="hazclick.gif";
    
imagen[0].si.src="si.gif";
    
    
imagen[1].no.src="no1.gif";
    
imagen[1].pincha.src="hazclick1.gif";
    
imagen[1].si.src="si1.gif";
    
    
imagen[2].no.src="no2.gif";
    
imagen[2].pincha.src="hazclick2.gif";
    
imagen[2].si.src="si2.gif";
    
    

//------------------------------------------------------------------------------------    
    
function cliqueo(esto,numero){
    
imagenAnterior.src=imagen[numeroAnterior].no.src;
    
imagenAnterior=esto;
    
numeroAnterior=numero
    esto
.src=(esto.src!=imagen[numero].si.src)?imagen[numero].si.src:imagen[numero].no.src;
    }
    
    
</script>
    </head>

<body>
<a onfocus="this.blur()" href=#>
    <img     
            border=0 
            src="no.gif" 
            onclick="cliqueo(this,0)"
            onmouseover="if (this.src==imagen[0].no.src){this.src=imagen[0].pincha.src}"
            onmouseout="if (this.src==imagen[0].pincha.src){this.src=imagen[0].no.src}"
            >
</a>

<a onfocus="this.blur()" href=#>
    <img     border=0 
            src="no1.gif" 
            onclick="cliqueo(this,1)"
            onmouseover="if (this.src==imagen[1].no.src){this.src=imagen[1].pincha.src}"
            onmouseout="if (this.src==imagen[1].pincha.src){this.src=imagen[1].no.src}"
            >
</a>

<a onfocus="this.blur()" href=#>
    <img     border=0 
            src="no2.gif" 
            onclick="cliqueo(this,2)"
            onmouseover="if (this.src==imagen[2].no.src){this.src=imagen[2].pincha.src}"
            onmouseout="if (this.src==imagen[2].pincha.src){this.src=imagen[2].no.src}"
            >
</a>
</body>
</html> 
__________________
Cómo escribir

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

Última edición por KarlanKas; 04/01/2005 a las 11:50
  #125 (permalink)  
Antiguo 29/04/2003, 11:28
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
127.- Rellenar cajas de texto con select de un pop up

P.- Cómo rellenar cajas de texto con elementos seleccionados de un pop up?

R.- Con este código:

Tema:Formularios

Código PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<
html>
<
head>
    <
title>Untitled</title>
    <
script>
//Script original de KarlanKas para forosdelweb.com

    
camisa=["Seleccione...","Roja","Verde","Amarilla"];
    
pantalon=["Seleccione...","De campana","pitillo","chino","pata de elefante"]
    
sombrero=["Seleccione...","De Ala Ancha","Hongo","Chistera","Boina","Gorra"]

    function 
elegir(esto){

    
lista=esto.value
    opcion
=eval(lista);
    
codigo='<select style="font: normal 10px/20px verdana; color: navy" name="opciones" onChange="opener.formulario.enviar.disabled=false;opener.formulario.que'+lista+'.value=unescape(this.options.value); self.close()" >';
    for (
a=0;a<opcion.length;a++){
    
codigo+="<option value="+escape(opcion[a])+">"+opcion[a]+"</option>\n";
    }
    
codigo+="</select>";

    
pepe=window.open('','','width=200,height=50');
    
pepe.document.write("<html>");
    
pepe.document.write("<head>");
    
pepe.document.write("    <title>Elige Opción</title>");
    
pepe.document.write("</head>");
    
pepe.document.write('<body bgcolor="#ffffcc">');
    
pepe.document.write(codigo);
    
pepe.document.write("</body>");
    
pepe.document.write("</html>");
    }
    
    
</script>
</head>

<body>
<form action="javascript:alert('Enviandooo!!')"
      name="formulario"
      id="formulario"
      style="font: normal 10px/20px verdana; color: navy"
      title="Elige que comprar">
      <input type="radio"
             name="opcion"
             value="camisa"
             onClick="elegir(this)">camisa<br>
    <input style="border:solid 1px black" type="text"
           name="quecamisa"
           readonly><br>
           
    <input type="radio"
             name="opcion"
             value="pantalon"
             onClick="elegir(this)">pantalón<br>
             
    <input style="border:solid 1px black" type="text"
           name="quepantalon"
           readonly><br>
                
    <input type="radio"
             name="opcion"
             value="sombrero"
             onClick="elegir(this)">sombrero<br>
             
    <input style="border:solid 1px black" type="text"
           name="quesombrero"
           readonly><br><br>
           
    
                      
    <input     style="heigth:15px;font: normal 10px/10px verdana; color: navy"
            type="submit"
            id="enviar"
           value="Enviar!"
           disabled>  
      </form>


</body>
</html> 
__________________
Cómo escribir

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

Última edición por KarlanKas; 04/01/2005 a las 11:52
  #126 (permalink)  
Antiguo 29/04/2003, 16:46
 
Fecha de Ingreso: diciembre-2001
Ubicación: Santo Domingo, R.D.
Mensajes: 240
Antigüedad: 22 años, 3 meses
Puntos: 0
128. Como mostrar 4 imagenes de la BDs para luego hacer navegacion con MouseOver?

La respuesta

Código PHP:
<head>
<
script>

function 
changeimage(towhat,url){
if (
document.images){
document.images.targetimage.src=towhat.src
gotolink
=url
}
}
function 
warp(){
window.location=gotolink
}

</script>

<script language="JavaScript1.1">
var myimages=new Array()
var gotolink="#"

function preloadimages(){
for (i=0;i<preloadimages.arguments.length;i++){
myimages[i]=new Image()
myimages[i].src=preloadimages.arguments[i]
}
}
</script>
</head>

Esto dentro del body para la precarga de las imagenes:


<script>
    preloadimages("<%=rs("foto1")%>","<%=rs("foto2")%>","<%=rs("foto3")%>","<%=rs("foto4")%>")
</script>


Aqui va la imagen mas grande que sera reemplazada por las de abajo cuando se haga el mouseover:
ponerla donde quiera 

<a href="javascript:warp()"><img src="<%= rs("foto1") %>" name="targetimage" border=0 width=175 height=200></a>

Y esto donde van las imagenes para hacer el mouse over:

<td><a href="verfoto.asp?id=<%=rs("id")%>" onMouseover="changeimage(myimages[0],this.href)">
  <img src="<%=rs("foto1") %>" border=0 width="36" height="41"></a></td>

<td><a href="verfoto.asp?id=<%=rs("id")%>" onMouseover="changeimage(myimages[1],this.href)"> 
  <img src="<%= rs("foto1") %>" border=0 width="36" height="41"></a></td>

<td><a href="verfoto.asp?id=<%=rs("id")%>" onMouseover="changeimage(myimages[2],this.href)"> 
  <img src="<%= rs("foto1") %>" border=0 width="36" height="41"></a></td>

<td><a href="verfoto.asp?id=<%=rs("id")%>" onMouseover="changeimage(myimages[3],this.href)"> 
  <img src="<%= rs("foto1") %>" border=0 width="36" height="41"></a></td> 
__________________
Alan Muñoz
www.mbsolucionesweb.com
Soluciones, programación y diseño web

Última edición por KarlanKas; 29/04/2003 a las 17:17
  #127 (permalink)  
Antiguo 30/04/2003, 21:57
 
Fecha de Ingreso: febrero-2002
Ubicación: Santiago
Mensajes: 253
Antigüedad: 22 años, 1 mes
Puntos: 0
129.- Validar Campo Vacio

P.- Como validar que un campo sea vacio,aunque se haya presionado la barra espaciadora ?

R.-

Código:
<html>
<head>
<script language="JavaScript">
<!-- 
function verificar()
{
if(form1.nombre_campo.value.replace(/ /g, '') == '')
{
alert("Debe Ingresar un valor ");
form1.nombre_campo.focus();
form1.nombre_campo.select();
return false;
}
}
-->
</script>
<title>Validar Campo Vacio</title>
</head>
<body>
<form name="form1">
<input name="nombre_campo" type="text" size="15" maxlength="15">
<input type="button" name="Validar" value="Validar" onclick="verificar()">
</form>
</body>
</html>

Última edición por Renegado; 30/04/2003 a las 22:05
  #128 (permalink)  
Antiguo 01/05/2003, 01:44
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 21 años, 11 meses
Puntos: 1284
130. Fondo degradado

P .- Como puedo poner un fondo degradado en una página.

R .- Poniendo mediante un script que en primer lugar averigue las dimensiones de la página, y luego inserte en una capa vacía una tabla vacía pero con el fondo de cada celda con distinto color.
Los tamaños de las celdas, se calculan a partir de los datos del tamaño de la página, y los colores se generan dinámicamente.

Ejemplo:

Código PHP:
<html>
<
head>
<
title>
    
Degradado
</title>
<
script language=javascript>
function 
color(n)    {
    return 
"0123456789ABCDEF".charAt(parseInt(16)) + "0123456789ABCDEF".charAt(parseInt(16));
}

function 
ini()    {
    var 
elFondo document.getElementById("fondo").style;
    var 
ancho document.body.clientWidth;
    var 
alto =  document.body.clientHeight;
    
elFondo.width ancho;
    
elFondo.height alto;
    var 
altoCelda alto 256;
    var 
tabla "<table cellpadding=0 cellspacing=0 width=100% height=100%>";
    for (var 
255>= 0--)
        
tabla += "<tr><td width=100% height=" altoCelda " style='background-color: #FF" color(i) + "00' ></td></tr>"
    
tabla += "</table>";
    
document.getElementById("fondo").innerHTML tabla;
}
</script>
 </head>
<body style="margin:0" onresize=ini() onload="ini()">
<div style="position: relative">
<div id=fondo style="position:absolute; top:0; left:0;"></div>
<div id=general style="position:absolute; top:0; left:0;">
<table border=1>
<tr>
<td >
Tabla sin importancia
</td></tr></table>
<div>
</div>
</body>
</html> 
Para que funcione con otros colores y otro nº de pasos intermedios, se puede usar otra FAQ: http://www.forosdelweb.com/showthrea...567#post903567

Y quedaría así:
Código:
<html> 
<head> 
<title> 
    Degradado 
</title> 
<script language=javascript src="gradientes.js"> 
</script>
<script language=javascript> 

function ini()    { 
    var colores = transitar("ff0000", "0000ff", 256);
    var elFondo = document.getElementById("fondo").style; 
    var ancho = document.body.clientWidth; 
    var alto =  document.body.clientHeight; 
    elFondo.width = ancho; 
    elFondo.height = alto; 
    var altoCelda = alto / 256; 
    var tabla = "<table cellpadding=0 cellspacing=0 width=100% height=100%>"; 
    for (var i = 0; i < colores.length; i ++) 
        tabla += "<tr><td width=100% height=" + altoCelda + " style='background-color: " + colores[i] + "' ></td></tr>" 
    tabla += "</table>"; 
    document.getElementById("fondo").innerHTML = tabla; 
} 
</script> 
</head> 
<body style="margin:0" onresize=ini() onload="ini()"> 
<div style="position: relative"> 
<div id=fondo style="position:absolute; top:0; left:0;"></div> 
<div id=general style="position:absolute; top:0; left:0;"> 
<table border=1> 
<tr> 
<td > 
Tabla sin importancia 
</td></tr></table> 
<div> 
</div> 
</body> 
</html>
Notas: Deben indicarse los colores y el nº de pasos en la función transitar:
var colores = transitar("ff0000", "0000ff", 256);
Es preferible no usar un número de pasos muy grande para evitar una ralentización innecesaria.


Última edición por caricatos; 18/12/2004 a las 05:02
  #129 (permalink)  
Antiguo 06/05/2003, 15:22
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
131.- Validar la entrada de un campo numérico y dar formato al resultado

P: ¿Como puedo hacer una entrada de datos donde se valide el ingreso de caracteres numéricos o los signos ",.-" y que al salir del mismo aparezca el resultado con decimales y formato para los miles?

Créditos: Mackpipe

R: [ver ejemplo]

Código PHP:
<html>
 <
head>
  <
script>
   function 
NumberFormat(numnumDecdecSepthousandSep){
    var 
arg;
    var 
Dec;
    
Dec Math.pow(10numDec); 
    if (
typeof(num) == 'undefined') return; 
    if (
typeof(decSep) == 'undefined'decSep ',';
    if (
typeof(thousandSep) == 'undefined'thousandSep '.';
    if (
thousandSep == '.')
     
arg=/./g;
    else
     if (
thousandSep == ','arg=/,/g;
    if (
typeof(arg) != 'undefined'num num.toString().replace(arg,'');
    
num num.toString().replace(/,/g'.'); 
    if (
isNaN(num)) num "0";
    
sign = (num == (num Math.abs(num)));
    
num Math.floor(num Dec 0.50000000001);
    
cents num Dec;
    
num Math.floor(num/Dec).toString(); 
    if (
cents < (Dec 10)) cents "0" cents
    for (var 
0Math.floor((num.length - (i)) / 3); i++)
     
num num.substring(0num.length - (3)) + thousandSep num.substring(num.length - (3));
    if (
Dec == 1)
     return (((
sign)? '''-') + num);
    else
     return (((
sign)? '''-') + num decSep cents);
   } 

   function 
EvaluateText(cadenaobj){
    
opc false
    if (
cadena == "%d")
     if (
event.keyCode 47 && event.keyCode 58)
      
opc true;
    if (
cadena == "%f"){ 
     if (
event.keyCode 47 && event.keyCode 58)
      
opc true;
     if (
obj.value.search("[.*]") == -&& obj.value.length != 0)
      if (
event.keyCode == 46)
       
opc true;
    }
    if(
opc == false)
     
event.returnValue false
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   numero
   <input type="text" name="input1" size="15" value="500034567" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')"><br><br>
  </form>
 </body>
</html> 

Última edición por Kaopectate; 07/05/2003 a las 11:44
  #130 (permalink)  
Antiguo 08/05/2003, 01:45
Avatar de davidvamo  
Fecha de Ingreso: diciembre-2001
Ubicación: Barcelona '92
Mensajes: 106
Antigüedad: 22 años, 3 meses
Puntos: 0
132.- Cambiar color a las celdas de una tabla

P: ¿Como puedo alterar el color de una celda donde se ha producido un click, retornando luego al color original cuando se produzca un click en otra celda?

R:
Código PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<
html>
<
head>
    <
title>Untitled</title>
    <
SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
  <!--
        var 
celda_ant;
        
        
celda_ant="";
        
      function 
ilumina(celda){
          if (
celda_ant=="")
            {
                
celda_ant celda;
            }
          
celda_ant.style.backgroundColor="green";
            
celda.style.backgroundColor="yellow";
            
celda_ant celda;
        }
  
//-->
  
</SCRIPT>
</head>

<body>

<table border="1" width="50%">
    <tr>
        <td bgcolor="green" onclick="ilumina(this)">rrr</td>
        <td bgcolor="green" onclick="ilumina(this)">iii</td>
        <td bgcolor="green" onclick="ilumina(this)">rrr</td>
        <td bgcolor="green" onclick="ilumina(this)">iii</td>
    </tr>
    <tr>
        <td bgcolor="green" onclick="ilumina(this)">rrr</td>
        <td bgcolor="green" onclick="ilumina(this)">iii</td>
        <td bgcolor="green" onclick="ilumina(this)">rrr</td>
        <td bgcolor="green" onclick="ilumina(this)">iii</td>
    </tr>
</table>

</body>
</html> 

Última edición por Kaopectate; 12/05/2003 a las 09:51
  #131 (permalink)  
Antiguo 12/05/2003, 12:52
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
133.- Llenar un campo de un formulario desde un popup

P: ¿Como puedo llenar un campo de un formulario a partir de un valor seleccionado en un popup?

R: [ver ejemplo]

Formulario.htm
Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
   function 
buscar(){
    
open("Popup.htm");
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td align="right">
      Editorial
     </td>
     <td>
      <input type="text" name="editorial">
      <input type="button" value="buscar" onclick="buscar()"><br>
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

Popup.htm
Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
   var 
seleccionado "";
   var 
aEdit = new Array(
                
"MacGraw_Hill",
                
"Microsoft_Press",
                
"Salvat"
               
);

   function 
cambiaSel(chk){
    
seleccionado chk.value;
   }

   function 
envia(){
    
opener.document.frm.editorial.value seleccionado;
    
close();
   }
  
</script>
 </head>
 <body>
  <form name="frm2">
   <script language="JavaScript">
    for (var i = 0; i < aEdit.length; i++)
     document.write("<input type='radio' name='ed' value='" + aEdit[i] + "' onclick='cambiaSel(this)'>" + aEdit[i] + "<br>");
   </script>
   <input type="button" name="enviar" value="Enviar" onclick="envia()">
  </form>
 </body>
</html> 
  #132 (permalink)  
Antiguo 13/05/2003, 07:07
Avatar de joseisrael  
Fecha de Ingreso: noviembre-2002
Ubicación: Maracay, Edo. Aragua
Mensajes: 221
Antigüedad: 21 años, 4 meses
Puntos: 1
134.- Trabajando con Múltiples Checkbox

P: ¿Cómo Selecciono o Desmarco Varios Checkbox al mismo tiempo?

R:

Cita:
Este Código va en el Header

Código:
<SCRIPT LANGUAGE="JavaScript">

<!-- Begin
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "Uncheck All"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "Check All"; }
}
// End -->
</script>
-----------------------

Cita:
Este Código va dentro del BODY
Código:
<form name="name">

<input type="checkbox" name="SLT_ALL" value="Check All" onClick="this.value=check(this.form.lista)">

<input type="checkbox" name="lista" value="a">
<input type="checkbox" name="lista" value="b">
<input type="checkbox" name="lista" value="c">
<input type="checkbox" name="lista" value="d">
<input type="checkbox" name="lista" value="e">
<input type="checkbox" name="lista" value="f">

</form>

Este Script lo consegui en:

<!-- Modified By: Steve Robison, Jr. ([email protected]) -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

Suerte
__________________
Aprender Siempre. Lema de Vida

José Molina

Última edición por joseisrael; 13/05/2003 a las 10:42
  #133 (permalink)  
Antiguo 28/05/2003, 14:38
Avatar de Carlitos
Usuario no validado
 
Fecha de Ingreso: mayo-2001
Ubicación: Zaragoza
Mensajes: 1.304
Antigüedad: 22 años, 10 meses
Puntos: 25
135.- Rotador de banner

P.- ¿Cómo puedo realizar un rotador de banners sencillo?

R.- Probado en: IE 5+, Netscape 7, Opera 7, Firefox 1[Ejemplo]

Código:
<script>
// Rotador de banner's . Carlitos. [email protected]

var ban = new Array()
var enl = new Array()
var indice = 0

ban[0] = new Image()
ban[0].src = "mdw.gif"
enl[0] = "http://www.maestrosdelweb.com"

ban[1] = new Image()
ban[1].src = "faq.gif"
clara[1] = "http://www.faqsdelweb.com"

ban[2] = new Image()
ban[2].src = "script.gif"
enl[2] = "http://www.webtutorial.com.ar/scriptmaster/"

ban[3] = new Image()
ban[3].src = "webest.gif"
enl[3] = "http://www.webestilo.com"

function rota()
{
if (indice ==  ban.length) indice = 0

if (document.images)
 {
  document.images.fotico.src = ban[indice].src  
 }
else
 {
  document.getElementById('fotico').src=ban[indice].src
 }
indice++
setTimeout('rota()',2000)
}
function vete()
{
window.open(enl[indice-1])
}
</script>
<body onload=rota()>
<img src="" id="fotico" onclick="vete()">

Última edición por Carlitos; 09/07/2005 a las 10:42
  #134 (permalink)  
Antiguo 06/06/2003, 14:48
 
Fecha de Ingreso: diciembre-2002
Mensajes: 65
Antigüedad: 21 años, 3 meses
Puntos: 0
136.- Agregar elementos dinámicamente

P: ¿Como puedo agregar dinámicamente en una forma, elementos tipo text y textarea?

R:

Código PHP:
<html>
<
head>
<
title>Form Page</title>
<!-- 
Javascript code for the dynamic form elements. -->
<
script>
    
// Declare the form field count javascript variable so you know how many the user have added.
    //The CGI.REQUEST_METHOD bit is the CF code for setting this variable back to the count where it was last up to.
    
var tFormFieldCount 1;
    var 
tFormFieldList "";
    
    
// Function to dynamically insert the form field to the cell below. If you want textareas or other form elements, just create another function and change the html insert text below.
    
function MakeOne(FieldType) {
        
// Depending on what type of form fields the user choose then dynamically write the appropriate form element to the page
        
if (FieldType == 'TextInput') {
            
document.getElementById('DynamicContent').innerHTML += 'Form Element ' tFormFieldCount '- Text input box&nbsp;&nbsp;<input type="text" name="TextInput' tFormFieldCount '"><br>';
        } else if (
FieldType == 'Textarea') {
            
document.getElementById('DynamicContent').innerHTML += 'Form Element ' tFormFieldCount '- Textarea&nbsp;&nbsp;<textarea name="Textarea' tFormFieldCount '" cols=30 rows=3></textarea><br>';
        }
        
        
// Populate the form element list.
        
if (tFormFieldList == "") {
            
tFormFieldList FieldType;
        } else {
            
tFormFieldList += "," FieldType;
        }
        
        
document.forms[0].FormFieldCount.value tFormFieldCount;
        
document.forms[0].FormFieldList.value tFormFieldList;
        
tFormFieldCount++;
    }
    
    
// Just a function to check if the user have added any text input fields.
    
function CheckIt() {
        if (
tFormFieldCount == 1) {
            
alert('You must add at least one text input field.');
            return 
false;
        }
    return 
true;
    }
</script>
</head>

<body bgcolor="#FFFFFF">
<!-- HTML form tag. -->
<!-- Action attribute specify where the form data is to be sent to  -->
<!-- Method attribute specify what method the form data is to be sent. POST or GET. Default is GET. -->
<form action="ResultsPage.cfm" method="post" onSubmit="return CheckIt();">
    <table cellspacing=0 cellpadding=4 border=1>
        <tr><td align="right"><input type="button" value="Add Form Text Fields" onClick="MakeOne('TextInput');">&nbsp;&nbsp;<input type="button" value="Add Form Textarea" onClick="MakeOne('Textarea');"></td></tr>
        <tr>
            <td id="DynamicContent" valign="top">
                <!-- Cold fusion code again to test to see if the request method of this page is POST or GET. -->
                <!-- If is POST then you know is from the result page and there's data to be output. -->
                
            </td>
        </tr>
        <tr>
            <td align="right" colspan=2>
                <!-- Hidden form field to pass the count of the text inputs to the result page. -->
                <input type="hidden" name="FormFieldList">
                <input type="hidden" name="FormFieldCount">
                <input type="submit" value="Send It">
            </td>
        </tr>
    </table>
</form>
</body>
</html> 

Última edición por Kaopectate; 09/06/2003 a las 16:41
  #135 (permalink)  
Antiguo 11/06/2003, 15:24
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
137.- Comparar las palabras de dos listas

P: ¿Como puedo comparar las palabras de un elemento textarea respecto a las palabras existentes en otro textarea?

R:

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">

   function 
separa(sTxtsSep){
    var 
sTx2 "";
    var 
bPalabra false;
    for (var 
0sTxt.lengthj++){
     if (
sSep.indexOf(sTxt.charAt(j)) != -1){
      if (
bPalabrasTx2 += " ";
      
bPalabra false;
     } else {
      
bPalabra true;
      
sTx2 += sTxt.charAt(j);
     }
    }
    return 
sTx2;
   }

   function 
comunes(aIzqaDer){
    var 
ijnRessPal;
    
nRes 0;
    
sPal "";
    for (
0aIzq.lengthi++)
     for (
0aDer.lengthj++)
      if (
aIzq[i] == aDer[j])
       if (
sPal.indexOf(aIzq[i]) == -1){
        
nRes++;
        
sPal += " " aIzq[i];
       }
    
document.frm.comunes.value String(nRes);
   }

   function 
soloEnA(aIzqaDer){
    var 
ijnRessPalbPresente;
    
nRes 0;
    
sPal "";
    for (
0aIzq.lengthi++){
     
bPresente false;
     for (
0; (aDer.length) && !bPresentej++)
      
bPresente = (aIzq[i] == aDer[j])
     if (!
bPresente && (sPal.indexOf(aIzq[i]) == -1)){
      
nRes++;
      
sPal += " " aIzq[i];
     }
    }
    
document.frm.soloA.value String(nRes);
   }

   function 
soloEnB(aIzqaDer){
    var 
ijnRessPalbPresente;
    
nRes 0;
    
sPal "";
    for (
0aDer.lengthi++){
     
bPresente false;
     for (
0; (aIzq.length) && !bPresentej++)
      
bPresente = (aDer[i] == aIzq[j])
     if (!
bPresente && (sPal.indexOf(aDer[i]) == -1)){
      
nRes++;
      
sPal += " " aDer[i];
     }
    }
    
document.frm.soloB.value String(nRes);
   }

   function 
calcula(){
    var 
sIzqsDeraIzqaDer;
    
sIzq separa(document.frm.texto.value";.,:");
    
sDer separa(document.frm.diccionario.value";.,:");
    
sIzq sIzq.replace(/[rnf]/g" ");
    
sDer sDer.replace(/[rnf]/g" ");
    
aIzq sIzq.split(" ");
    
aDer sDer.split(" ");
    
comunes(aIzqaDer);
    
soloEnA(aIzqaDer);
    
soloEnB(aIzqaDer);
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td align="center">
      Area A
     </td>
     <td align="center">
      Area B
     </td>
    </tr>
    <tr>
     <td align="left">
      <textarea name="texto" onkeyup="calcula()"></textarea>
     </td>
     <td align="right">
      <textarea name="diccionario" onkeyup="calcula()"></textarea>
     </td>
    </tr>
    <tr>
     <td colspan="2" align="center">
      <table border="0">
       <tr>
        <td align="left">
         En A y no en B
        </td>
        <td align="center">
         Comunes
        </td>
        <td align="right">
         En B y no en A
        </td>
       </tr>
       <tr>
        <td align="left">
         <input type="text" name="soloA">
        </td>
        <td align="center">
         <input type="text" name="comunes">
        </td>
        <td align="right">
         <input type="text" name="soloB">
        </td>
       </tr>
      </table>
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

Última edición por Kaopectate; 11/06/2003 a las 15:21
  #136 (permalink)  
Antiguo 13/06/2003, 12:13
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
138.- Manipulación de strings

P: ¿Como puedo eliminar los espacios en blanco del comienzo o del final de una cadena?

R:

Código PHP:
<html>
 <
head>
   <
script language="JavaScript">

    function 
lTrim(sStr){
     while (
sStr.charAt(0) == " "
      
sStr sStr.substr(1sStr.length 1);
     return 
sStr;
    }

    function 
rTrim(sStr){
     while (
sStr.charAt(sStr.length 1) == " "
      
sStr sStr.substr(0sStr.length 1);
     return 
sStr;
    }

    function 
allTrim(sStr){
     return 
rTrim(lTrim(sStr));
    }

    function 
prueba(){
     
with (document.frm){
      
original.value ">" usuario.value "<";
      
lTrimmed.value ">" lTrim(usuario.value) + "<";
      
rTrimmed.value ">" rTrim(usuario.value) + "<";
      
allTrimmed.value ">" allTrim(usuario.value) + "<";
     }
    }

   
</script>
  </head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td align="right">
      Valor
     </td>
     <td>
      <input type="text" name="usuario" value="    Un valor      "><br>
     </td>
    </tr>
    <tr>
     <td align="right">
      Original
     </td>
     <td>
      <input type="text" name="original" readonly><br>
     </td>
    </tr>
    <tr>
     <td align="right">
      Trim izquierdo
     </td>
     <td>
      <input type="text" name="lTrimmed" readonly><br>
     </td>
    </tr>
    <tr>
     <td align="right">
      Trim derecho
     </td>
     <td>
      <input type="text" name="rTrimmed" readonly><br>
     </td>
    </tr>
    <tr>
     <td align="right">
      Trim completo
     </td>
     <td>
      <input type="text" name="allTrimmed" readonly><br>
     </td>
    </tr>
    <tr>
     <td colspan="2" align="center">
      <input type="button" value="Calcula" onclick="prueba()">
     </td>
    </tr>
   </table>
  </form>
 </body>
</html> 

Última edición por Kaopectate; 13/06/2003 a las 12:13
  #137 (permalink)  
Antiguo 24/06/2003, 17:53
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
139.- Calendario

P: ¿Como puedo poner un calendario para seleccionar los campos fecha?

R:

Calendario.htm
Código PHP:
<html>
 <
head>
  <
script language="JavaScript">

   var 
dFec = new Date();
   var 
aMonthNames = new Array(
                          
"January""February""March""April""May""June",
                          
"July""August""September""October""November""December");

   function 
firstOfMonth(dFec){
    var 
dRes = new Date();
    
dRes.setYear(dFec.getYear());
    
dRes.setMonth(dFec.getMonth());
    
dRes.setDate(1);
    return 
dRes;
   }

   function 
lastDayOfMonth(dFec){
    var 
dRes = new Date();
    var 
nYear dFec.getYear();
    var 
nMonth dFec.getMonth() + 1;
    if (
nMonth == 12){
     
nMonth 0;
     
nYear++;
    }
    
dRes.setYear(nYear);
    
dRes.setMonth(nMonth);
    
dRes.setDate(1);
    return new 
Date(dRes.valueOf() - (24 60 60 1000));
   }

   function 
dayToWrite(nDay){
    var 
dToday = new Date();
    var 
bisThisMonth = ((dFec.getYear() == dToday.getYear()) && (dFec.getMonth() == dToday.getMonth()));
    var 
sDay String(nDay);
    
sDay = (nDay == dFec.getDate() && bisThisMonth"<b><font color='red'>" sDay "</font></b>"sDay);
    return 
sDay;
   }

   function 
selectDay(nDay){
    var 
sRessDaysMonsYea;
    
sDay "0" String(nDay);
    
sDay sDay.substr(sDay.length 22);
    
sMon "0" String(dFec.getMonth() + 1);
    
sMon sMon.substr(sMon.length 22);
    
sYea String(dFec.getFullYear());
    
sRes sDay "/" sMon "/" sYea;
    
opener.document.forms[0].dateResult.value sRes;
    
opener.fillDateField();
    
close();
   }

   function 
showCalenContents(){
    var 
dFec0 firstOfMonth(dFec);
    var 
nDay 1;
    var 
nLastDay lastDayOfMonth(dFec).getDate();
    var 
sWeek "";
    var 
bEnd false;
    var 
bWri false;
    var 
nDOW0 dFec0.getDay();
    for (var 
0; !bEndj++){
     
sWeek "<tr>";
     for (var 
0; (7) && !bEndi++){
      
bWri bWri || (== nDOW0);
      if (
bWri)
       
sWeek += "<td align='right' style='cursor: hand' onclick='parent.selectDay(" String(nDay) + ")'>" dayToWrite(nDaybWri) + "</td>";
      else
       
sWeek += "<td>&nbsp;</td>";
      if (
bWrinDay++;
      
bEnd = (nDay nLastDay);
     }
     if (
bEnd
      for (var 
i7k++)
       
sWeek sWeek "<td>&nbsp;&nbsp;</td>";
     
window.usefull.document.writeln(sWeek "</tr>");
    }
   }

   function 
backMonth(){
    var 
nMonth dFec.getMonth();
    var 
nYear dFec.getFullYear();
    if (--
nMonth == -1){
     
nMonth 11;
     
nYear--;
    }
    
dFec.setMonth(nMonth);
    
dFec.setYear(nYear);
    
calendary();
   }

   function 
forthMonth(){
    var 
nMonth dFec.getMonth();
    var 
nYear dFec.getFullYear();
    if (++
nMonth == 12){
     
nMonth 0;
     
nYear++;
    }
    
dFec.setMonth(nMonth);
    
dFec.setYear(nYear);
    
calendary();
   }

   function 
backYear(){
    var 
nYear dFec.getFullYear();
    
dFec.setYear(--nYear);
    
calendary();
   }

   function 
forthYear(){
    var 
nYear dFec.getFullYear();
    
dFec.setYear(++nYear);
    
calendary();
   }

   function 
showCalen(){
    
with (window.usefull.document){
     
write("<table border='0' width='100%' height='100%'><tr><td><table border='0' width='100%'><tr>");
     
write("<td width='10'><input type='button' name='bckYear' value='<<' onclick='parent.backYear()'></td>");
     
write("<td width='10'><input type='button' name='bckMonth' value='<' onclick='parent.backMonth()'></td>");
     
write("<td align='center'><b>" aMonthNames[dFec.getMonth()].substr(03) + ", " String(dFec.getYear()) + "</b></td>");
     
write("<td width='10'><input type='button' name='ForMonth' value='>' onclick='parent.forthMonth()'></td>");
     
write("<td width='10'><input type='button' name='ForYear' value='>>' onclick='parent.forthYear()'></td>");
     
write("</tr></table></tr><tr><td>");
     
write("<table border='0'>");
     
write("<tr><td><b>Su</b></td><td><b>Mo</b></td><td><b>Tu</b></td><td><b>We</b></td><td><b>Th</b></td><td><b>Fr</b></td><td><b>Sa</b></td></tr>");
     
showCalenContents();
     
write("</table></td></tr></table>");
    }
   }

   function 
calendary(){
    
with (window.usefull.document){
     
open();
     
writeln("<html><head></head><body>");
     
writeln("<form name='frm'>");
     
showCalen();
     
writeln("</form></body></html>");
     
close();
    }
   }

  
</script>
 <head>
 <frameset rows="100%,*" border="0" frameborder="no" framespacing="0" onload="calendary()">
  <frame name="usefull" src="DummyPg.htm" frameborder="no" marginheight="0" marginwidth="0" scrolling="no">
  <frame name="useless" src="DummyPg.htm" frameborder="no" marginheight="0" marginwidth="0" scrolling="no">
 </frameset>
<html> 
Modo de uso: testCalen.htm
Código PHP:
<html>
 <
head>
  <
script language="JavaScript">

   var 
nInput;

   function 
calen(n){
    var 
oWnd;
    
nInput n;
    
oWnd open("Calendario.htm""fechas""location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,width=180,height=200");
    
oWnd.focus();
   }

   function 
fillDateField(){
    
with (document.frm)
     if (
nInput == 1)
      
fechaInicial.value dateResult.value;
     else
      
fechaFinal.value dateResult.value;
   }

  
</script>
 <head>
 <body>
  <form name="frm">
   <table border="0">
    <tr>
     <td>
      Desde
     </td>
     <td>
      <input type="text" name="fechaInicial">
      <input type="button" value="..." onclick="calen(1)">
     </td>
    </tr>
    <tr>
     <td>
      Hasta
     </td>
     <td>
      <input type="text" name="fechaFinal">
      <input type="button" value="..." onclick="calen(2)">
     </td>
    </tr>
   </table>
   <input type="hidden" name="dateResult">
  </form>
 <body>
<html> 
Página "dummy": DummyPg.htm
Código PHP:
<html>
 <
head>
 </
head>
 <
body>
 </
body>
</
html
  #138 (permalink)  
Antiguo 30/06/2003, 11:00
Avatar de Mickel  
Fecha de Ingreso: mayo-2002
Ubicación: Lima, Peru
Mensajes: 4.619
Antigüedad: 21 años, 10 meses
Puntos: 7
140. P:Como validar que se seleccionen solo archivos de determinado tipo en un INPUT TYPE='FILE'?

R:
Usa esta funcion
Código PHP:
function LimitAttach(tField,iType) {
file=tField.value;
if (
iType==1) {
extArray = new Array(".gif",".jpg",".png");
}
if (
iType==2) {
extArray = new Array(".swf");
}
if (
iType==3) {
extArray = new Array(".exe",".sit",".zip",".tar",".swf",".mov",".hqx",".ra",".wmf",".mp3",".qt",".med",".et");
}
if (
iType==4) {
extArray = new Array(".mov",".ra",".wmf",".mp3",".qt",".med",".et",".wav");
}
if (
iType==5) {
extArray = new Array(".html",".htm",".shtml");
}
if (
iType==6) {
extArray = new Array(".doc",".xls",".ppt");
}
allowSubmit false;
if (!
file) return;
while (
file.indexOf("\\") != -1file file.slice(file.indexOf("\\") + 1);
ext file.slice(file.indexOf(".")).toLowerCase();
for (var 
0extArray.lengthi++) {
if (
extArray[i] == ext) {
allowSubmit true;
break;
}
}
if (
allowSubmit) {
} else {
tField.value="";
alert("Usted sólo puede subir archivos con extensiones " + (extArray.join(" ")) + "\nPor favor seleccione un nuevo archivo");
}

de tal forma que en tu input type='file' agreges
onBlur='LimitAttach(this,n);' donde n es el tipo de validacion que deseas hacer

Nota. Los tipos de validaciones mostrados son
1: gif, jpg, png
2: swf
3: exe, sit, zip, tar, swf, mov, hqx, ra, wmf, mp3, qt, med, et
4: mov, ra, wmf, mp3, qt, med, et, wav
5: htm, html, shtml
6: doc, xls, ppt
pero pueden agregarse o cambiarse segun se necesiten

Última edición por KarlanKas; 30/06/2003 a las 15:06
  #139 (permalink)  
Antiguo 30/06/2003, 11:44
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 1 mes
Puntos: 772
141.- Calcular el tiempo que tarda en cargarse una página.

P: ¿Como puedo poner en una página el tiempo que ha tardado en cargarse en el navegador del usuario?

R:
Código PHP:
<html>
<
head>
<
script>
var 
inicio=new Date();
inicio=inicio.getTime();
function 
ini() {
    
fin=new Date();
    
fin=fin.getTime();
    
tiempo=(fin-inicio)/1000//Gracias por el consejo, Ferny
    
document.getElementById('tmp').innerHTML=tiempo;
}
</script>
</head>

<body onLoad="ini()">
Tiempo que ha tardado la página en cargarse: <span id="tmp">Calculando...</span> segundos.
</body>
</html> 

Última edición por JavierB; 14/11/2003 a las 14:56
  #140 (permalink)  
Antiguo 08/07/2003, 14:36
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
142.- Generar dinámicamente campos de texto

P: ¿Como puedo generar sobre mi página un número distinto de campos de texto según lo que indique el usuario?

R:

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">

   var 
nValores 0;

   function 
cambiaPg(){
    
with (window.pantalla.document){
     
nValores parseInt(frm.cant.value10);
    }
    
formulario();
   }

   function 
formulario(){
    
with (window.pantalla.document){
     
open();
     
writeln("<html>\n<body>");
     
writeln("<form name='frm'>");
     
writeln(" Número de textos:");
     
writeln(" <input type='text' name='cant'>");
     
writeln(" <input type='button' name='btn' value='Aplicar' onclick='parent.cambiaPg()'>");
     
writeln("<br>");
     for (var 
0nValoresi++){
      
writeln("Valor " String(i) + ":");
      
writeln("<input type='text' name='c" String(i) + "'><br>");
     }
     
writeln("</form>");
     
writeln("</body>\n</html>");
     
close();
    }
   }

   
document.writeln("<frameset rows='100%,*' onload='javascript:parent.formulario()'>");
   
document.writeln("     <frame name='pantalla' src='DummyPage.htm'>");
   
document.writeln("     <frame src=''>");
   
document.writeln("</frameset>");

  
</script>
 </head>
</html> 
  #141 (permalink)  
Antiguo 07/08/2003, 09:06
Avatar de ferny
Il capo della mafia
 
Fecha de Ingreso: febrero-2002
Ubicación: Al final del cable
Mensajes: 10.080
Antigüedad: 22 años, 1 mes
Puntos: 55
143.- Previsualizar una imagen antes de subirla

P: ¿Se puede previsualizar una imagen que he seleccionado en un <input type=file> antes de subirla?

R:

SI:

Código PHP:
<p>Selecciona una imagen</p>
<
input type="file" onChange="document.imagen.src='file:///' + this.value"><br><br>
Vista previa:<br><br>
<
img src="imagenpordefecto.gif" name="imagen"
Ver ejemplo

Nota: sólo funcionará en Internet Explorer
__________________
www.mundodivx.com || www.mundodivx.org

Pon tu mano en un horno caliente durante un minuto y te parecerá una hora.
Siéntate junto a una chica preciosa durante una hora y te parecerá un minuto.
Eso es la relatividad.

Última edición por ferny; 10/11/2006 a las 07:48 Razón: Añadida una nota al final
  #142 (permalink)  
Antiguo 12/08/2003, 18:21
Avatar de CsC_3  
Fecha de Ingreso: noviembre-2002
Mensajes: 589
Antigüedad: 21 años, 4 meses
Puntos: 0
144.- Meter archivo txt en una pagina web

P: Se puede meter un archivo txt, en una pagina web?

R: pero que claro que si.

esto va en cualquier parte donde quieras meter el txt
Código PHP:

<script language="javascript" src="diario.txt"></script> 
esto debe de ir en el txt

Código PHP:
 var saludo=""+
"<font color=#ffffff size=2>script, para meter un txt<br>"+

"<font color=#333333 size=2>en un html, sin problemas</font>"+

"<font color=#ffffff size=1>CsC3</font>";

document.write(saludo); 

este codigo tiene la libertad que puedes meter, texto (con formato), imagenes, etc...




[se que no soy moderador, ni nada del foro de jscript, pero este codigo se me hace muy facil y practico, perdon si hago mal, en ponerlo]
__________________
"No hay emoticon que describa lo que siento en estos momentos!!!"

Última edición por Kaopectate; 24/05/2004 a las 14:59
  #143 (permalink)  
Antiguo 24/08/2003, 04:15
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
145.- Ver la página a distintas resoluciones

P.- ¿Cómo puedo ver si mi página se verá bien a una resolución menor que la que tiene mi PC sin tener que cambiar la configuración de la pantalla de mi ordenador?
R.- Esto es un pequeño truco que se vale de la posibilidad de ejectar sentencias de JS en la barra de Dirección del navegador. Sólo se debe, una vez en la página que queremos ver a otra resolución, poner en la barra de dirección:



En realidad no debe ser 600 el alto, debería ser 540 poruqe con la barra de inicio se pierde un espacio (valioso) que ha de tenerse en cuenta. El ejemplo es para todos los que tenemos la pantalla a 1024x768 o superior y tenemos la fastidiosa labor de hacer páginas a 800x600.

Un saludo!
__________________
Cómo escribir

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

Última edición por KarlanKas; 25/08/2003 a las 04:42
  #144 (permalink)  
Antiguo 28/08/2003, 08:36
 
Fecha de Ingreso: agosto-2003
Mensajes: 12
Antigüedad: 20 años, 7 meses
Puntos: 0
146.- Forzar entrada por la página principal (sin usar marcos)

P: ¿Cómo puedo forzar que el usuario entre siempre por mi página principal (index.htm) y no por mis páginas secundarias si NO utilizo marcos (frames)?

R: Con este script .

En el HEAD de la página secundaria a la que no quieres que entren sin pasar por index.htm:

Código PHP:
<script language="JavaScript">
function 
redireccionar() {
    var 
origen document.referrer;
    if (
origen!="http://tuweb/index.htm"window.location.href"index.htm";
    }
</script> 
Y en el BODY de esa misma página, poner al principio del todo:
Código PHP:
<body onactivate="redireccionar()"
Notas: el valor de la variable origen debe ser la URL completa incluyendo la página "de control", y el `window.location.href apunta a "index.htm" directamente porque la página que contiene el script se encuentra en el mismo directorio que "index.htm". Si no es así, poner la ruta.

Salu2 y gracias a Kaopectate por la "pista clave" .

Última edición por Kaopectate; 29/08/2003 a las 13:25
  #145 (permalink)  
Antiguo 09/09/2003, 06:26
Avatar de epa2  
Fecha de Ingreso: abril-2002
Ubicación: Málaga
Mensajes: 1.475
Antigüedad: 21 años, 11 meses
Puntos: 9
147.- Mensaje segun hora del día

P: ¿COMO PUEDO MOSTRAR UN MENSAJE EN MI PAGINA DEPENDIENDO DE LA HORA DEL DIA?

R:Con este pequeño script

CREDITOS BRAVENET

Código:
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
document.write("<div align='center' style='font:bold 14px verdana;'>")
day = new Date()
hr = day.getHours()
if (hr == 1) document.write("It's after 1 am. Are you still up?")
if (hr == 2) document.write("It's after 2 am. Are you still up?")
if (hr == 3) document.write("It's after 3 am. Are you still up?")
if (hr == 4) document.write("It's after 4 am. Are you still up?")
if (hr == 5) document.write("It's after 5 am. Are you still up?")
if (hr == 6) document.write("It's after 6 am, yawn!")
if (hr == 7) document.write("Good Morning! It's after 7 am")
if (hr == 8) document.write("It's after 8 am")
if (hr == 9) document.write("It's after 9 am")
if (hr == 10) document.write("It's after 10 am, coffee time!")
if (hr == 11) document.write("It's after 11 am")
if (hr == 12) document.write("It's after noon")
if (hr == 13) document.write("Good Afternoon! It's after 1 pm")
if (hr == 14) document.write("It's after 2 pm")
if (hr == 15) document.write("It's after 3 pm")
if (hr == 16) document.write("It's after 4 pm")
if (hr == 17) document.write("Good Evening! It's after 5 pm")
if (hr == 18) document.write("It's after 6 pm, eat some dinner!")
if (hr == 19) document.write("It's after 7 pm")
if (hr == 20) document.write("It's after 8 pm")
if (hr == 21) document.write("It's after 9 pm")
if (hr == 22) document.write("It's after 10 pm")
if (hr == 23) document.write("It's after 11 pm, go to bed!")
if (hr == 0) document.write("It's after midnight.")
document.write("</div>")
// End -->
</SCRIPT>
__________________

***Aprendiz de todo y maestro de nada***

Última edición por Kaopectate; 24/05/2004 a las 15:00
  #146 (permalink)  
Antiguo 26/09/2003, 10:22
Avatar de acervantes  
Fecha de Ingreso: agosto-2003
Ubicación: Madrid
Mensajes: 311
Antigüedad: 20 años, 7 meses
Puntos: 1
148.- Formato Fecha

P: ¿Cómo puedo mostrar la fecha en formato "28 de Septiembre del 2003"?

R: Con esta función de javascript:

CREDITOS: seoista

Código PHP:
<html>
 <
head>
  <
script language="JavaScript">
   
// función que muestra la fecha en formato Viernes, 26 de Septiembre del 2003
   // parámetro una fecha (se asume que es válida)

   
function showdate(mydate){
    var 
year mydate.getYear()
    if (
year 1000)
     
year += 1900
    
var day mydate.getDay()
    var 
month mydate.getMonth()
    var 
daym mydate.getDate()
    if (
daym 10)
     
daym "" daym
    
var dayarray = new Array("Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado")
    var 
montharray = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")
    return 
dayarray[day] + ", " daym " de " montharray[month] + " del " year;
   }

   
// y la llamada a la función
   
document.write(showdate(new Date()))
  
</script>
 </head>
 <body>
 </body>
</html> 
__________________
ACervantes

[El éxito dura hasta que alguien las caga; los errores son eternos]

Última edición por Kaopectate; 26/09/2003 a las 12:59
  #147 (permalink)  
Antiguo 30/09/2003, 03:42
Avatar de Helbira  
Fecha de Ingreso: octubre-2001
Ubicación: Sevilla, España
Mensajes: 1.228
Antigüedad: 22 años, 5 meses
Puntos: 5
149.- Límite de caracteres en un textarea

P: ¿Cómo puedo limitar el número de caracteres de un textarea?

R: La solución no es el atributo maxlength que tiene los campos de texto. Consiste en cada vez que se introduzca un carácter en el textarea, contar el número total de caracteres que van ya escritos y en caso de haberse superado, borrar el último carácter.

Código PHP:
<script language="JavaScript">
function 
maximaLongitud(texto,maxlong) {
  var 
teclain_valueout_value;

  if (
texto.value.length maxlong) {
    
in_value texto.value;
    
out_value in_value.substring(0,maxlong);
    
texto.value out_value;
    return 
false;
  }
  return 
true;
}
</script>

<textarea name="nombre_textarea" cols="50"
rows="5" onKeyUp="return maximaLongitud(this,254)"> 

Última edición por Helbira; 30/09/2003 a las 03:50
  #148 (permalink)  
Antiguo 30/09/2003, 15:22
Avatar de Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 22 años, 3 meses
Puntos: 38
150.- Detectar Sistema Operativo

P: ¿Como puedo saber el Sistema Operativo sobre el que esta corriendo mi página?

R:

Código PHP:
<html>
 <
head>
  <
script LANGUAGE="JavaScript">

   function 
getOpSys(){
    var 
sOpSys "<b>O.S.: </b>" navigator.appVersion.toLowerCase().split(";"3)[2];
    return 
sOpSys;
   }

  
</script>
  <title></title>
 </head>
 <body>
  <script language="JavaScript">
   document.writeln(getOpSys());
  </script>
 </body>
</html> 
  #149 (permalink)  
Antiguo 03/10/2003, 06:22
Avatar de JavierB
Colaborador
 
Fecha de Ingreso: febrero-2002
Ubicación: Madrid
Mensajes: 25.052
Antigüedad: 22 años, 1 mes
Puntos: 772
151.- Controlar el número de decimales de un número.

P: ¿Como puedo mostrar un número con una determinada cantidad de decimales?

R: Con este pequeño código:
Código PHP:
<html>
<
head>
<
script>
Number.prototype.decimal = function (num) {
    
pot Math.pow(10,num);
    return 
parseInt(this pot) / pot;
}
function 
decimal(src) {
    
n=eval(document.getElementById(src).value);
    
alert(n.decimal(3)); //deja 3 decimales
}
</script>
</head>

<body>
<input type="text" id="numero" value="3.1415926">
<input type="button" onClick="decimal('numero')">
</body>
</html> 

Última edición por JavierB; 05/12/2003 a las 13:03
  #150 (permalink)  
Antiguo 03/10/2003, 09:26
Avatar de KarlanKas
Moderador extraterrestre
 
Fecha de Ingreso: diciembre-2001
Ubicación: Madrid
Mensajes: 6.987
Antigüedad: 22 años, 3 meses
Puntos: 61
152.- Cómo tener un WHOIS siempre a mano

P.- Muchas veces necesitamos saber si un dominio está libre o comprobar cuando un dominio de un cliente caduca y tenemos que visitar la típica página de unvendedor de dominios, solicitarlo y darle al whois cuando nos dice que (obviamente) está ocupado. ¿No hay una forma más sencilla?
R.- Sí la hay, pega este código en la barra de dirección de tu navegador, a continuación pincha en el espacio de la derecha de dicha barra donde suele aparecer el icono de página web (en el explorer una hoja con una e delante) y arrástralo hasta la barra de vínculos.

Código PHP:
javascript:pepe=prompt("nombre del dominio","","");document.location("http://www.dnsstuff.com/tools/whois.ch?ip="+pepe); 
La dirección la saqué de un post de cvdhs. Gracias, "jefe".
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
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.
Tema Cerrado

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




La zona horaria es GMT -6. Ahora son las 15:26.