Foros del Web

Foros del Web (http://www.forosdelweb.com/)
-   Javascript (http://www.forosdelweb.com/f13/)
-   -   FAQs JavaScript (http://www.forosdelweb.com/f13/faqs-javascript-105325/)

Adler 30/06/2008 14:52

Respuesta: Validar E-Mail
 
Código PHP:

function vMail(ce) {
var 
okemce.email.value;

var 
localOK = /^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/;
var ipOK = /^[?[0-9.]+]?$/;
var 
dominoOK = /^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/;

// El email consta de dos partes dividas por @
var email_array okem.split('@');

if (
email_array.length || email_array.length 2) {
alert("La dirección de email 1  ("email_array.length +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }

// Incorrecto número de caracteres en alguna de las dos partes
if (email_array[0].length  || email_array[1].length  1) {
alert("La dirección de email 2 ("email_array[0].length +") -- ("email_array[1].length +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }

var 
local_array email_array[0].split('.');
for (
0local_array.lengthi++)
{
if (!
localOK.test(local_array[i])) {
alert("La dirección de email 3 ("local_array[i] +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }
}

// Se revisa si el dominio es una IP. Si no, debe ser un nombre de dominio válido
if (!ipOK.test(okem)) {

var 
dominio_array email_array[1].split('.');
// Incorrecto número de secciones por exceso o defecto para ser un dominio
if (dominio_array.length || dominio_array.length 3) {
alert("La dirección de email 4 ("dominio_array.length +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }

for (
0dominio_array.lengthi++)
{
if (!
dominoOK.test(dominio_array[i])) {
alert("La dirección de email 5 ("dominio_array[i] +") no es válida.");
       
document.forms.sendmail.email.focus();
       return (
false);
    }
        }
}
else
return (
true)


Mismo código en php

Mismo código en asp

andrewp 27/07/2008 01:57

Respuesta: FAQs JavaScript
 
Pregunta: Cómo puedo validar un grupo de radio buttons?
Respuesta: Respuesta complementada por XBX:

En el header deberías incluir el siguiente código:

Código PHP:

<script language="javascript">
function 
query_validator(){
    var 
isOneChecked false;
    for (var 
i=0document.form.grupo.lengthi++)
    {
         if(
document.form.grupo[i].checked){
            
isOneChecked true;
            break;
         }
    }

    if (!
isOneChecked) {
        
alert('Por favor, seleccione una respuesta');
         return(
false);
    }
}
</script> 

En el body de tu página debes inclmuír la siguiente acción en el inicio del formulario:

Código PHP:

<form name="form3" action="respuestas.php" method="post" onsubmit="return query_validator();">
... 
Aqui el resto de tu codigo con el grupo de radio buttons incluido ...
</
form


marcopoloaz06 05/08/2008 11:39

274.- PUNTEROS en un Array
 
P:¿ Cómo usar las funciones de PHP current(),next(),prev(),end(),reset(), en JavaScript ?
R: [EJEMPLO]

asi:
Código HTML:

<script type="text/javascript">
(function(){
// PUNTEROS ARRAY
Array.prototype.currentNum = 0;
Array.prototype.current = function(){
    return this[ this.currentNum ];
};
Array.prototype.next = function(){
    return this.currentNum+1<this.length ? this[ ++this.currentNum ] : false;
};
Array.prototype.prev = function(){
    return this.currentNum-1>
0 ? this[ --this.currentNum ] : false;
};
Array.prototype.end = function(){
    return this.length>0 ? this[ this.currentNum = this.length-1 ] : false;
};
Array.prototype.reset = function(){
    return this[ this.currentNum = 0 ];
};
})();
</script>

pueden ver el ejemplo

Saludos
:]

marcopoloaz06 13/08/2008 22:58

275.- ¿Cómo hacer un Enum?
 
P:¿Cómo hacer un Enum como en otros lenguajes de programación?
R: asi:

Código PHP:

    function Enum(nombRevaloRes){
        
window[nombRe] = {};
        for(var 
i=j=0;i<valoRes.length;i++,j++){
            var 
valoRes[i].split("-");
            
window[nombRe][( s.length>) ? s[0] : valoRes[i] ] = ( s.length>) ? j=Numbers[1] ) : j;
        }
    };
    
Enum.isDefined = function( Enumval ){
        for( 
x in Enum ){
            if( 
x==val ) return Enum[x];
        }
        return -
1;
    };
    
// EJEMPLOS
    
Enum"maRco", ["a""as""asd""asdf""asdfg""asdfgh"] );
     
maRco = {a0, as: 1asd2asdf3asdfg4asdfgh5};
    
Enum"pOlo", ["z-1""y""x"] )
     
pOlo = {z1y2x3};
    
Enum"aZ", ["x-1""xd""xD-10""XD""Xd-20""d"] );
     
aZ = {x1xd2xD10XD11Xd20d:21};
    
Enum.isDefinedaZ"XD" );
     
// return 11; 

Saludos &
adios...
;]

Panino5001 07/09/2008 15:53

Respuesta: FAQs JavaScript
 
P: Cómo logar un efecto espejo con javascript?
R: Usando Canvas para los navegadores estandar y un filtro propietario para explorer. Ejemplo . Código del ejemplo
Código PHP:

<!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=iso-8859-1" />
<
title>test</title>
<
script>
function 
reflejo (contenedorimagen) {
        var 
ref false;
        if (
document.createElement("canvas").getContext) {
            
/* ---- canvas ---- */
            
ref document.createElement("canvas");
            
ref.width imagen.width;
            
ref.height imagen.height;
            var 
context ref.getContext("2d");
            
context.translate(0imagen.height);
            
context.scale(1,-1);
            
context.drawImage(imagen00imagen.widthimagen.height);
            
ref.style.opacity '0.35';
        } else {
            
/* ---- DXImageTransform ---- */
            
ref=document.createElement('img');
            
ref.src=imagen.src;
            
ref.style.filter 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=50, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=' imagen.height ')';
        
ref.widthimagen.width;
        
ref.heightimagen.height;
        }
        
ref.style.position 'absolute';
        
ref.style.left0;
        
ref.style.topimagen.height+'px'
        
contenedor.appendChild(ref);
    }
window.onload=function(){
    
reflejo(document.getElementById('pp'), document.getElementById('ll'));
}
</script>
</head>

<body>
<div id="pp" style="position:relative"><img id="ll" src="5.jpg" width="180" height="144" /></div>
</body>
</html> 

Si bien el efecto está bastante logrado, podemos mejorarlo haciendo que el resultado en navegadores estandar se parezca más al que obtenemos en Explorer, aplicando gradientes como hace este último en su filtro. Este sería el resultado final.
Y este el código utilizado:
Código PHP:

<!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=iso-8859-1" />
<
title>test</title>
<
script>
function 
reflejo (contenedorimagen) {
        var 
ref false;
        if (
document.createElement("canvas").getContext) {
            
/* ---- canvas ---- */
            
ref document.createElement("canvas");
            
ref.width imagen.width;
            
ref.height imagen.height;
            var 
context ref.getContext("2d");
            
context.translate(0imagen.height);
            
context.scale(1,-1);
            
context.drawImage(imagen00imagen.widthimagen.height);
            
context.globalCompositeOperation "destination-out";
            var 
gradient context.createLinearGradient(000imagen.height);
            
gradient.addColorStop(0"rgba(255, 255, 255, 1.0)");
            
gradient.addColorStop(1"rgba(255, 255, 255, 0.1)");
            
context.fillStyle gradient;
            
context.fillRect(0,0,imagen.widthimagen.height);
        } else {
            
/* ---- DXImageTransform ---- */
            
ref=document.createElement('img');
            
ref.src=imagen.src;
            
ref.style.filter 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=50, style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=' imagen.height ')';
        
ref.widthimagen.width;
        
ref.heightimagen.height;
        }
        
ref.style.position 'absolute';
        
ref.style.left0;
        
ref.style.topimagen.height+'px'
        
contenedor.appendChild(ref);
    }
window.onload=function(){
    
reflejo(document.getElementById('pp'), document.getElementById('ll'));
}
</script>
</head>

<body>
<div id="pp" style="position:relative"><img id="ll" src="5.jpg" width="180" height="144" /></div>
</body>
</html> 

(Probado en Explorer, Safari, Ópera, Firefox y Chrome)

Panino5001 07/09/2008 16:02

Respuesta: FAQs JavaScript
 
P: Se puede rotar una imagen usando javascript?
R: Sí, y más allá del camino chapucero que propuse en este post, la inclusión de soporte para el elemento html estandar llamado canvas en la mayoría de los navegadores modernos, junto a filtros propietarios del único navegador popular que no soporta dicho elemento, nos permiten tranquilamente realizar esta tarea. Ejemplo. Código del ejemplo:
Código PHP:

<!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=iso-8859-1" />
<
title>test</title>
<
script>
function 
rotar(obj,angulo){
    if (
angulo >= 0) {
        var 
rotation Math.PI angulo 180;
    } else {
        var 
rotation Math.PI * (360+angulo) / 180;
    }
    var 
costheta Math.cos(rotation);
    var 
sintheta Math.sin(rotation);
    if (
document.createElement("canvas").getContext) {
    
/* ---- canvas ---- */ 
        
var c=document.createElement('canvas');
        
c.width Math.abs(costheta*obj.width) + Math.abs(sintheta*obj.height);
        
c.style.width c.width+'px';
        
c.height Math.abs(costheta*obj.height) + Math.abs(sintheta*obj.width);
        
c.style.height=c.height+'px';
        
c.id=obj.id;
        
c.style.position='absolute';
        var 
ctx=c.getContext('2d');
        
ctx.save();
        if (
rotation <= Math.PI/2) {
            
ctx.translate(sintheta*obj.height,0);
        } else if (
rotation <= Math.PI) {
            
ctx.translate(c.width,-costheta*obj.height);
        } else if (
rotation <= 1.5*Math.PI) {
            
ctx.translate(-costheta*obj.width,c.height);
        } else {
            
ctx.translate(0,-sintheta*obj.width);
        }
        
ctx.rotate(rotation);
        
ctx.drawImage(obj00obj.widthobj.height);
        
obj.parentNode.replaceChild(c,obj);
        
ctx.restore();
    }else{
    
/* ---- DXImageTransform ---- */
        
obj.style.position='absolute';
        
obj.style.filter="progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand')";
        
obj.filters.item(0).M11 costheta;
        
obj.filters.item(0).M12 = -sintheta;
        
obj.filters.item(0).M21 sintheta;
        
obj.filters.item(0).M22 costheta;
    }
}
window.onload=function(){
    
rotar(document.getElementById('pp'),60);
    
}
</script>
</head>

<body>
<img src="1.jpg" width="180" height="127" />
<div id="ll" style="position:relative; "><img id="pp" src="1.jpg" width="180" height="127" /></div>
</body>
</html> 

(Ejemplo probado en Explorer, Safari, Ópera, Firefox y Chrome)

Raya2 07/10/2008 17:19

Respuesta: FAQs JavaScript
 
P: SOLO PARA CHILE - Validacion del RUT
R: Script siguiente
Lo unico a tener en cuenta es que el RUT debe ingresarse en el formato:
12345678-9
Código del ejemplo:
Código PHP:

function validaRut(rut){
    var 
rutlimpio "";
    for (
i=0rut.lengthi++){
        if ((
rut.charAt(i)!=".") && (rut.charAt(i)!="-"))
            
rutlimpiorutlimpio rut.charAt(i);
    }
    
rut=rutlimpio;
    var 
drut=rut.charAt((rut.length-1));
     var 
dvr='0';
    
suma=0;
    
mul=2;
    for (
i=rut.length ->= 0i--){
         
suma=suma rut.charAt(i) * mul
         
if (mul==7){
             
mul=2;
        }else{
             
mul++;
        }
     }
    
res suma &#37; 11;
    
if (res==1){
        
dvr 'k';
    }else if (
res==0){
        
dvr '0';
    }else{
         
dvi 11-res;
         
dvr dvi "";
     }
    if ((
dvr != drut.toLowerCase())){
         return 
false;
     }else{
        return 
true;
    }


(Ejemplo probado en Explorer y Firefox )

Distriker 25/02/2009 11:42

278. Crear un Pop-Up y variantes ScrollBar y MenuBar
 
P: ¿Cómo crear un Pop-Up e incluirle la barra de desplazamiento y la barra de estado?
R: Solamente deberías de seguir esto:

El codigo del Pop-Up es el siguiente:
Código:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420")
  3. </script>

Pruebalo
Recordatorio: Desactivar "Bloquear ventana emergente".

Los scripts hay que ponerlos entre las etiquetas <script></script>, recuerden esto para siempre ;-).

En el Pop-Up (ventana secundaria) puede tener varias variaciones. Una puede ser la de ponerle la barra de desplazamiento:

Ahora viene la pregunta, ¿Como se colocan esas barras de desplazamiento? Muy sencillo. Solo teneis que añadir despues de height y separando con una coma:

Código:
Código:

scrollbars=yes
o
scrollbars=1

Información: 1= Si - 0= No

Entonces, quedaría así:

Código:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420,scrollbars=yes")
  3. </script>
o así:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420,scrollbars=1")
  3. </script>

Pruebalo.
Recordatorio: Desactivar "ventana emergente".

También le podeis agregar la barra de estado, solamente añadiendo esto:

Código:
Código:

menubar=yes
o
Código:

menubar=1
Recuerden, si quereis que no tenga el menubar, no hace falta que se lo pongais ;-).

Quedaría así:

Código:
Código javascript:
Ver original
  1. <script>
  2. window.open("http://forosdelweb.com","","width=550,height=420,menubar=yes,scrollbars=yes")
  3. </script>

Pruebalo.
Recordatorio: Desactivar "ventana emergente".

¿Qué os parece? ¿Os ha gustado? ¿Os ha servido? ¿Alguna duda? Si es así, preguntadla.

En realidad, un Pop-Up suele ser una ventana sin nada o con el minimo, pero ustedes pueden buscar mas atributos que se le puedan atribuir a este sencillo codigo, venga, animense ;-).

Espero que os haiga gustado.

Puede que mas adelante publique mas de mis cosillas ;-).

Saludos

Creditos: Distriker

venkman 03/03/2009 12:50

Respuesta: FAQs JavaScript
 
Obtener el texto seleccionado.

Código html:
Ver original
  1.     <head>
  2.     <script type="text/javascript">
  3. function getTextoSeleccionado() {
  4.     if (window.getSelection) {
  5.         return window.getSelection();
  6.     } else if (document.getSelection) {
  7.         return document.getSelection();
  8.     } else if (document.selection) {
  9.         return document.selection.createRange().text;
  10.     } else return "Opción no soportada por el navegador";
  11. }
  12.     </script>
  13.  </head>
  14.  <body>
  15.   <form name="frm">
  16.    <table border="0">
  17.     <tr>
  18.      <td align="right">
  19.       input:
  20.      </td>
  21.      <td>
  22.       <input type="textInput" name="txt">
  23.      </td>
  24.     </tr>
  25.     <tr>
  26.      <td align="right">
  27.       textarea:
  28.      </td>
  29.      <td>
  30.       <textarea name="txtArea"></textarea>
  31.      </td>
  32.     </tr>
  33.     <tr>
  34.      <td align="right">
  35.       Link:
  36.      </td>
  37.      <td>
  38.       <a href="#">Enlace</a>
  39.      </td>
  40.     </tr>
  41.     <tr>
  42.      <td align="right">
  43.       Select:
  44.      </td>
  45.      <td>
  46.       <select>
  47.        <option>Uno</option>
  48.        <option>Dos</option>
  49.        <option>Tres</option>
  50.       </select>
  51.      </td>
  52.     </tr>
  53.     <tr>
  54.      <td align="right">
  55.       Párrafo:
  56.      </td>
  57.      <td>
  58.       Esto es un párrafo de donde también se puede seleccionar texto.
  59.      </td>
  60.     </tr>
  61.     <tr>
  62.      <td align="center" colspan="2">
  63.       <a href=javascript:void(alert(getTextoSeleccionado()))>Ver texto seleccionado</a>
  64.      </td>
  65.     </tr>
  66.   </form>
  67.  </body>
  68. </html>

En diferentes navegadores la selección de texto se maneja de forma diferente.


La zona horaria es GMT -6. Ahora son las 16:46.

Desarrollado por vBulletin® Versión 3.8.7
Derechos de Autor ©2000 - 2025, Jelsoft Enterprises Ltd.