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. USANDO Y MANEJANDO ACTIVEX I P1: Notas. ActiveX es una tenología que permite utilizar objetos OLE dentro de páginas web, siendo creados por Microsoft y ...

  #241 (permalink)  
Antiguo 10/10/2006, 05:09
Avatar de crcbad  
Fecha de Ingreso: enero-2005
Mensajes: 302
Antigüedad: 19 años, 3 meses
Puntos: 0
USANDO Y MANEJANDO ACTIVEX I

P1: Notas.

ActiveX es una tenología que permite utilizar objetos OLE dentro de páginas web, siendo creados por Microsoft y siendo válidos desde la versión 3.0 del IE.

Es una tecnología que en el mundo web está bastante mal usada, y es la fuente de incursión de muchos tipos de datos peligrosos en nuestro PC por tener acceso al sistema de fichero de la persona que ejecuta el ActiveX, por lo que por seguridad siempre se encuentra desactivada la opción de ejecutar ActiveX. No obstante, los antivirus y antytroyanos ayudan a que ningún código peligros pudiera entrar.

No obstante, tiene sus ventajas el acceder a dichas propiedades de la colección de ActiveX, y yo, voy a poner algún ejemplo de ello.

-------------------------------
P2: Apertura, Lectura y Cierra de un fichero.

La función a la que llamaremos es:

Código PHP:
function lecturaActiveX(directorio,archivo)
{
 
// Creamos objeto a la librería FileSystemObject
 
var objSystem = new ActiveXObject("Scripting.FileSystemObject");
 
 
// Comprobamos que el directorio exista
 
if (fso.folderexists(directorio) == false
  return 
false;
 
 else
 { 
  var 
rutaCompleta directorio fichero;
 
  
// Comprobamos que el fichero exista
  
if(objSystem.FileExists(rutaCompleta ) == false
   return 
false;
 
  else 
  {
   
// Abrimos el fichero con la ruta seleccionada
   
var objFichero objSystem.OpenTextFile(rutaCompleta ,1);
 
   
// Método para leer el contenido del fichero
   
var datosFichero objFichero.readall();
 
   
// Cierra de fichero
   
objFichero.close();
 
  
// Envío de la información, por ejemplo a un TextArea
   
return datosFichero 
  }
 }

Nota: Si en el directorio ponemos la ruta de nuestro PC con la barra "\" nos dará error, tenemos que escapar esa barra con "\\".

-------------------------------
P3: Apertura, Modificación y Cierre de un fichero.

Ahora lo mismo, pero modificando la información de un fichero con alguna nueva, es decir, haciendo una operación de agregación de datos, esta vez pondré un ejemplo tal cual tengo en un HTML:

Código PHP:
function guardadoInfo()
 
// Arreglo temporal con ActiveX para guardar el codigo en el fichero
 
modo 1;
 
 
// Esta línea la podéis quitar :P
 
rutaCompleta rTrim(app.replace(/Ç/g, '\\')) + nomFich;
 
 // Creamos objeto FileSystemObject
 
var fso = new ActiveXObject("Scripting.FileSystemObject");
 
 
// Caso de que no exista el fichero
 
if(fso.FileExists(rutaCompleta) == false && modo==0
  return 
false;
 
 
// Si estamos en modo append guardamos todo el contenido del fichero
 
if(fso.FileExists(rutaCompleta) != false && modo==2
 {
  
fich fso.OpenTextFile(rutaCompleta,1);
  
temporal fich.readall(); 
  
fich.close(); 
 }
 
 else 
  
temporal "";
 
 
// Objeto para crear un nuevo fichero con la info del antiguo más lo que queremos agregar
 
fich fso.CreateTextFile(rutaCompleta,2);
 
 
// Escribimos dicho contenido en el objeto fich
 
fich.write(temporal document.getElementById("codigo").innerText);
 
 
// Cierra del fichero
 
fich.close();

-------------------------------
P4: Ejecución de comandos mediante ActiveX.

Código PHP:
function ejecutaComando() 
{
 
// Creamos objeto shell
 
var objShell= new ActiveXObject("WScript.Shell");
 
 
// Parámetro 1 -> Ruta: Ruta completa con el comando a ejecutar
 // Parámetro 2 -> Modo: 0: Oculto, 1: normal, 2: minimizado, 3: maximizado, 4: normal sin foco 
 // Parámetro 3 -> Instancia: false:Múltiples instancias, true: Solo una.
 
 
var ejecuta objShell.run("C:\\ARCHIV~1\\OFFICE\\WORD.EXE, 2, true);
return ejecuta;

-------------------------------

Como véis, lo que se puede hacer es realmente grande, pero exige que el administrador de la máquina tiene una configuración bien realizada para que solamente ejecute ActiveX de confianza, bien de una determinada web, o bien de una determinada intraner, o bien de un determinado grupo de dominios.

Saludos
__________________

:cool: [ http://eruben.sytes.net ] :cool:


Las dos frases que te ayudarán a salir adelante:
  • No hay mujer fea, solo copas de menos. :borracho:
  • Ante la duda, siempre coge la más tetuda. :arriba:
  #242 (permalink)  
Antiguo 15/10/2006, 18:24
Avatar de urgido  
Fecha de Ingreso: febrero-2005
Mensajes: 2.351
Antigüedad: 19 años, 2 meses
Puntos: 25
P: Desactivar click derecho a las imágenes.
R: Con un poco de javascript esto es posible.

Código PHP:
<script language="JavaScript1.2">

var 
mensajealclick="El click derecho no esta permitido!"

function desactivarclick(e) {
if (
document.all) {
if (
event.button==2||event.button==3) {
if (
event.srcElement.tagName=="IMG"){
alert(mensajealclick);
return 
false;
}
}
}
else if (
document.layers) {
if (
e.which == 3) {
alert(mensajealclick);
return 
false;
}
}
else if (
document.getElementById){
if (
e.which==3&&e.target.tagName=="IMG"){
alert(mensajealclick)
return 
false
}
}
}

function 
imagenesasociadas(){
for(
i=0;i<document.images.length;i++)
document.images[i].onmousedown=desactivarclick;
}

if (
document.all)
document.onmousedown=desactivarclick
else if (document.getElementById)
document.onmouseup=desactivarclick
else if (document.layers)
imagenesasociadas()
</script> 
__________________
Hospedaje Web al mejor costo!
  #243 (permalink)  
Antiguo 27/10/2006, 02:17
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
añadir, cambiar y quitar opciones de un select

P.-¿Como añadir, cambiar y quitar opciones de un select por medio de javascript?
R.- Ver este hilo.
__________________
Cómo escribir

No hay pregunta tonta, sino tonto que quiere seguir en la ignorancia.
  #244 (permalink)  
Antiguo 28/10/2006, 07:54
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
245.-Sencillo editor bbCode

P:Cómo hacer un editor de bbCode sencillo que admita selección de texto?
R:
Código:
<html>
<head>
<title>Editor bbCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
function instag(tag){
var input = document.form1.contenido;
if(typeof document.selection != 'undefined' && document.selection) {
var str = document.selection.createRange().text;
input.focus();
var sel = document.selection.createRange();
sel.text = "[" + tag + "]" + str + "[/" +tag+ "]";
sel.select();
return;
}
else if(typeof input.selectionStart != 'undefined'){
var start = input.selectionStart;
var end = input.selectionEnd;
var insText = input.value.substring(start, end);
input.value = input.value.substr(0, start) + '['+tag+']' + insText + '[/'+tag+']'+ input.value.substr(end);
input.focus();
input.setSelectionRange(start+2+tag.length+insText.length+3+tag.length,start+2+tag.length+insText.length+3+tag.length);
return;
}
else{
input.value+=' ['+tag+']Reemplace este texto[/'+tag+']';
return;
}
}
function inslink(){
var input = document.form1.contenido;
if(typeof document.selection != 'undefined' && document.selection) {
var str = document.selection.createRange().text;
input.focus();
var my_link = prompt("Enter URL:","http://");
if (my_link != null) {
if(str.length==0){
str=my_link;
}
var sel = document.selection.createRange();
sel.text = "[a href=\"" + my_link + "\"]" + str + "[/a]";
sel.select();
}
return;
}else if(typeof input.selectionStart != 'undefined'){
var start = input.selectionStart;
var end = input.selectionEnd;
var insText = input.value.substring(start, end);
var my_link = prompt("Enter URL:","http://");
if (my_link != null) {
if(insText.length==0){
insText=my_link;
}
input.value = input.value.substr(0, start) +"[a href=\"" + my_link +"\"]" + insText + "[/a]"+ input.value.substr(end);
input.focus();
input.setSelectionRange(start+11+my_link.length+insText.length+4,start+11+my_link.length+insText.length+4);
}
return;
}else{
var my_link = prompt("Ingresar URL:","http://");
var my_text = prompt("Ingresar el texto del link:","");
input.value+=" [a href=\"" + my_link + "\"]" + my_text + "[/a]";
return;
}
}
</script>
</head>

<body>
<form name="form1" method="post" action="">
<input type="button" name="Submit" value="B" onClick="instag('b')">
<input type="button" name="Submit3" value="U" onClick="instag('u')">
<input type="button" name="Submit4" value=" I " onClick="instag('i')">
<input type="button" name="Submit2" value="LINK" onClick="inslink()">
<br>
<textarea name="contenido" cols="40" rows="10" id="contenido"></textarea>

</form>
</body>
</html>
Y algo más completo, en este enlace: bebecode
  #245 (permalink)  
Antiguo 06/11/2006, 14:00
 
Fecha de Ingreso: octubre-2004
Mensajes: 768
Antigüedad: 19 años, 6 meses
Puntos: 3
Rotador de Banners que acepta swf, gif y texto.

P: ¿Cómo puedo realizar un rotador de banners que acepte swf, gif y texto?
R: Aqui tienes un script que funciona perfectamente!!!
Creditos: Realizado por Fabian Muller y modificado por "djreficul" y una pequeña ayuda de "paulkees" para ForosdelWeb.com

Código HTML:
<html> <head> <title>Selección de Banners Aleatorios</title> </head> <body> <SCRIPT LANGUAGE="JavaScript"> // Realizado por: Fabian Muller y modificado por "djreficul" y una muy pequeña ayudita de "paulkees" de ForosdelWeb.com  // Comienzo var banners = 3; var ahora = new Date() var segundos = ahora.getSeconds() var ad = segundos % banners; ad +=1; if (ad==1) { flash="images/banners/240x74_anuncio.swf" width="295"; height="90"; } if (ad==2) { flash="images/bantrigoban.gif" width="289"; height="100"; url="http://www.rawk.com.ar"; txt="¡Conoce rawk.com.ar ahora!"; } if (ad==3) { flash="images/banners/foros_295x80.swf" width="295"; height="80"; } temp=flash.split("."); extension=temp[(temp.length-1)]; document.write('<center>'); if (extension=='swf') { document.write('<OBJECT CLASSID=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=' + width + ' height=' + height + ' CODEBASE=\"http://active.macromedia.com/flash4/cabs/swflash.cab#version=4,0,0,0\">'); document.write('<PARAM NAME=\"MOVIE\" VALUE=\"' + flash + '\">'); document.write('<PARAM NAME=\"PLAY\" VALUE=\"true\">'); document.write('<PARAM NAME=\"LOOP\" VALUE=\"true\">'); document.write('<PARAM NAME=\"QUALITY\" VALUE=\"high\">'); document.write('<EMBED SRC=' + flash + ' width=' + width + ' height=' + height + ' PLAY=\"true\" LOOP=\"true\" QUALITY=\"high\" PLUGINSPAGE=\"http://www.macromedia.com/shockwave/download/index.cgi? P1_Prod_Version=ShockwaveFlash\">'); document.write('</EMBED>'); document.write('</OBJECT>'); } else { document.write('<a href=\"' + url + '\" target=\"_blank\">'); document.write ('<img src="'+flash+'" width="'+width+'" height="'+height+'" border="0">'); document.write('<center><small>' + txt + '</small></center></a>'); } document.write('</center>'); // Fin </SCRIPT> </body> </html> 
  #246 (permalink)  
Antiguo 13/12/2006, 03:57
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: FAQs JavaScript

P: Como obtener el código de una letra (ASCII)
R: Con el método charCodeAt().

El método se aplica a elementos del tipo String (texto) y el parámetro que recibe es la posición del elemento.

Ejemplo:
"A".charCodeAt(0) = 65; (A)
"Hola".charCodeAt(3) = 97 (a)

El método inverso sería fromCharCode(), donde los parámetros son los códigos de los caracteres que se obtendrán.

Ejemplo:
String.fromCharCode(104, 111, 108, 97) = "hola"

__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #247 (permalink)  
Antiguo 30/12/2006, 17:38
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: FAQs JavaScript

P: Como borrar un input file
R: Por seguridad los campos file no son editables, pero se puede reemplazar por uno nuevo con el DOM

ver ejemplo:

Código:
<html>
	<head>
		<title>
			prueba
		</title>
		<script type="text/javascript">
			function valida(f) {
				if (f.value.substr(f.value.length - 3).toUpperCase() == "JPG")
					alert("Ok")
				else	{
					alert("No");
					siguiente = f.nextSibling;
					fff = document.createElement("input");
					fff.type = "file";
					fff.name = f.name;
					fff.onchange = f.onchange;
					fff.value = "";
					f.form.insertBefore(fff, siguiente);
					f.form.removeChild(f);
				}
			}
		</script>
	</head>
	<body >
		<form action="" method="get" name="f">
			<input type="file" name="jpg[0]" onChange="valida(this)"/>
			<input type="file" name="jpg[1]" onChange="valida(this)"/>
			<input type="file" name="jpg[2]" onChange="valida(this)"/>
			<input type="file" name="jpg[3]" onChange="valida(this)"/>
		</form>
	</body>
</html>
Se ha tratado el tema en estos enlaces: ¿cómo pongo un campo file vacio desde javascript? y Vaciar un campo de formulario

__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #248 (permalink)  
Antiguo 03/01/2007, 10:39
 
Fecha de Ingreso: diciembre-2006
Mensajes: 2
Antigüedad: 17 años, 4 meses
Puntos: 0
Re: FAQs JavaScript

A las varias FAQ sobre agregar reloj, agrego esta de mi cosecha: En la barra de direcciones:
Cita:
javascript:(function(){document.body.onmousemove=n ew Function("var d = new Date();var reloj=d.toLocaleString();this.title=reloj")})();
O en
Cita:
<body onmousemove="var d = new Date();var reloj=d.toLocaleString();this.title=reloj" >
  #249 (permalink)  
Antiguo 31/01/2007, 18:00
Avatar de derkenuke
Colaborador
 
Fecha de Ingreso: octubre-2003
Ubicación: self.location.href
Mensajes: 2.665
Antigüedad: 20 años, 6 meses
Puntos: 45
Re: FAQs JavaScript

P: ¿Cómo formateo un número con un separador de miles y uno de decimales? ¿Cómo vuelvo otra vez al formato original para operar?

R: He implementado unos cuantos métodos del objeto String para formatear un número con símbolos personalizados. format formatea y desFormat vuelve al estilo original.

Código:
<script language="Javascript">

String.prototype.reverse=function() { return this.split("").reverse().join(""); }
String.prototype.format=function(sepMil,sepDec) { 
	var partes=this.split(".");			//dividimos parte entera de decimal
	return partes[0].reverse().replace( /(\d{3})(?=\d)/g ,"$1"+sepMil).reverse() + (partes[1]?(sepDec + partes[1]):""); 
}
String.prototype.desFormat=function(sepMil,sepDec) {
	var reMil=new RegExp("\\"+sepMil,"g");		//para localizar los sepMil
	var reDec=new RegExp("\\"+sepDec);			//para localizar los sepDec
	return this.replace(reMil,"").replace(reDec,".").replace(/\s/g,"");
}

var numeros=[123.41, 1234.001, 123456.00, 123, 12345, 12345678901];


</script>

<table border="1">
	<script language="JavaScript">
	for(var a in numeros) {
		var n=numeros[a].toString();
		var fn=n.format(".","'");
		var dfn=fn.desFormat(".","'");
		document.writeln("<tr><td>" + n + "</td><td>" + fn + "</td><td>" + dfn + "</td></tr>");
	}
	</script>
</table>
Recordad que son métodos para String, ¡habremos de convetir los números a String con toString()!
__________________
- Haz preguntas inteligentes, y obtendrás más y mejores respuestas.
- Antes de postearlo Inténtalo y Búscalo.
- Escribe correctamente tus mensajes.

Última edición por derkenuke; 31/01/2007 a las 18:01 Razón: La etiqueta [ p h p ] elimina las backslashes (\\)
  #250 (permalink)  
Antiguo 31/01/2007, 19:08
Avatar de derkenuke
Colaborador
 
Fecha de Ingreso: octubre-2003
Ubicación: self.location.href
Mensajes: 2.665
Antigüedad: 20 años, 6 meses
Puntos: 45
Re: FAQs JavaScript

P: ¿Cómo formateo "al vuelo" mientras el usuario escribe en su caja de texto?

R:

Código:
<script language="Javascript">

String.prototype.reverse=function() { return this.split("").reverse().join(""); }
String.prototype.format=function(sepMil,sepDec) { 
	var partes=this.split(".");			//dividimos parte entera de decimal
	return partes[0].reverse().replace( /(\d{3})(?=\d)/g ,"$1"+sepMil).reverse() + (partes[1]?(sepDec + partes[1]):""); 
}
String.prototype.desFormat=function(sepMil,sepDec) {
	var reMil=new RegExp("\\"+sepMil,"g");		//para localizar los sepMil
	var reDec=new RegExp("\\"+sepDec);			//para localizar los sepDec
	return this.replace(reMil,"").replace(reDec,".").replace(/\s/g,"");
}

//escogemos los separadores que queramos
var SEPMIL=".";
var SEPDEC="'";
document.write("Utiliza un "+SEPDEC+" como separador de decimales.<br/>");

</script>

<input type="text" onkeyup="handler(event,this)" />

<script language="javascript">

function handler(e,caja) {
	//obtener la tecla pulsada
	var code = (window.Event) ? e.which : e.keyCode;
    var tecla = String.fromCharCode(code);
	if(caja.value.lastIndexOf(SEPDEC)==caja.value.length-1)		//se ha escrito SEPDEC, dejar empezar a escribir decimales
		return;		
	else if( "1234567890".indexOf(tecla)>-1) {					//se ha escrito un numero
		caja.value=caja.value.desFormat(SEPMIL,SEPDEC).format(SEPMIL,SEPDEC);
		return;
	}
}
</script>
__________________
- Haz preguntas inteligentes, y obtendrás más y mejores respuestas.
- Antes de postearlo Inténtalo y Búscalo.
- Escribe correctamente tus mensajes.
  #251 (permalink)  
Antiguo 02/04/2007, 04:55
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
251.-Selección en Textarea

P: Cómo seleccionar parte del contenido de un textarea sin usar el mouse?
R:
Código:
<!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>ejemplo</title> 
<script> 
function sel(inicio,fin){ 
input=document.getElementById('area'); 
if(typeof document.selection != 'undefined' && document.selection){ 
tex=input.value; 
input.value=''; 
input.focus(); 
var str = document.selection.createRange(); 
input.value=tex; 
str.move('character', inicio); 
str.moveEnd("character", fin-inicio); 
str.select(); 
} 
else if(typeof input.selectionStart != 'undefined'){ 
input.setSelectionRange(inicio,fin); 
input.focus(); 
} 
} 
</script> 
</head> 

<body> 
<form id="form1" name="form1" method="post" action=""> 
  <textarea name="area" cols="60" rows="10" id="area">esta es una prueba</textarea> 
  <input type="button" name="Submit" value="seleccionar" onclick="sel(8,11)" /> 
</form> 
</body> 
</html>
Ejemplo probado en Safari, Explorer, Firefox y Ópera
  #252 (permalink)  
Antiguo 02/05/2007, 02:28
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: FAQs JavaScript

P: ¿Como recoger Datos por url?
R: Para datos simples se puede usar otro mensaje de estas FAQs: Recoger valores de un formulario, pero para recoger arrays se puede con el código de este mensaje: Recibiendo array por url

Pego a continuación una de las versiones (creo que la más corta):

Código:
function receptor()	{
	var entrada = new Object();
	if (location.href.indexOf("?") == -1) return;
	params = location.search.substr(1).split("&");
	for (var i = 0, total = params.length; i < total; i ++)	{
		pareja = params[i].split("="); dato = unescape(pareja[1]);
		switch	(typeof(entrada[pareja[0]]))	{
			case "undefined": entrada[pareja[0]] = dato; break;
			case "object": entrada[pareja[0]][entrada[pareja[0]].length] = dato; break;
			case "string": temp = [entrada[pareja[0]], dato]; entrada[pareja[0]] = temp; break;
		}
	}
	for (i in entrada)	window[i] = entrada[i];
}
Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #253 (permalink)  
Antiguo 13/05/2007, 07:15
Avatar de nicolaspar  
Fecha de Ingreso: noviembre-2004
Ubicación: Villa Ballester Bs-As|Ar
Mensajes: 2.002
Antigüedad: 19 años, 5 meses
Puntos: 34
Re: FAQs JavaScript

Pregunta: Como reproducir un sonido con eventos?
Respuesta:
Código:
<!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>Reproducir sonido - By Nicolás Pardo 2007</title>

<script>
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/*Namespaces*/
var Media = document.Media || {};
// funciones para cookies

Media.PlaySound = {
    MSIE: navigator.userAgent.indexOf("MSIE"),
    NETS: navigator.userAgent.indexOf("Netscape"),
    OPER: navigator.userAgent.indexOf("Opera"),
    cookieName:  "cookie_sound_active",
    imgOn: "images/ico_on.gif",
    imgOff: "images/ico_off.gif",
    Sound: "_sonido.wav",
    WriteCookie: function( name, value ){
        var expdate=new Date();
        expdate.setTime(expdate.getTime()+10*365*24*60*60*1000);
        document.cookie = name + "=" + escape (value) + "; expires=" + expdate.toGMTString();
    },
    ReadCookie: function( name ){
        var namearg = name + "=";
        var nlen = namearg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + nlen;
            if (document.cookie.substring(i, j) == namearg) {
                var endpos = document.cookie.indexOf (";", j);
                if (endpos == -1) endpos = document.cookie.length;
                return unescape(document.cookie.substring(j, endpos));
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return null;
    },
    OnOffSound: function( img ){
        newValue = Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == 1 || Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == null  ? 0 : 1;
        img.src = newValue == 1 ? Media.PlaySound.imgOn : Media.PlaySound.imgOff;
        Media.PlaySound.WriteCookie( Media.PlaySound.cookieName, newValue );
    },
    SetMediaIE: function(){
        if((Media.PlaySound.MSIE>-1) || (Media.PlaySoundOPER>-1)) {
            document.write('<bgsound loop="0" name="MediaMyMediaObj" id="MediaMyMediaObj" >');
        }
    },
    PlayNow: function(){
    if( Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == 1 || Media.PlaySound.ReadCookie( Media.PlaySound.cookieName ) == null ){
        obj = MM_findObj("MediaMyMedia");
            if((Media.PlaySound.MSIE>-1) || (Media.PlaySoundOPER>-1)) {
                obj = MM_findObj("MediaMyMediaObj");
                obj.src = Media.PlaySound.Sound;
            } else {
                obj = MM_findObj("MediaMyMediaDiv");
                obj.innerHTML = '<embed  src="'+Media.PlaySound.Sound+'" hidden="true" volume="200" loop="0" type="audio/midi" >';
            }
        }
    }
}

Media.PlaySound.SetMediaIE();
</script>
</head>
<body>
<a href="#"><img src="images/ico_on.gif" onclick="Media.PlaySound.OnOffSound(this)" border="0" /></a>
<br />

<div name="MediaMyMediaDiv" id="MediaMyMediaDiv" style="margin:0; width:0; height:0;"></div>
<input type="button" value="dame" onclick="Media.PlaySound.PlayNow()" />
</body>
</html>
http://snipplr.com/view.php?codeview&id=2384

Testeado en IE y FF
__________________
Mi punto de partida es Que Bueno Lo Nuevo
  #254 (permalink)  
Antiguo 13/05/2007, 07:23
Avatar de nicolaspar  
Fecha de Ingreso: noviembre-2004
Ubicación: Villa Ballester Bs-As|Ar
Mensajes: 2.002
Antigüedad: 19 años, 5 meses
Puntos: 34
Re: FAQs JavaScript

Pregunta: Puedo eliminar la selección (encuadre) de los A?. Un ejemplo para explicar mejor el problema:

Código:
<!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>Documento sin t&iacute;tulo</title>

</head>

<body>
<a href="asa.hh">Test link</a>
</body>
</html>
Guarden esto, y verán que al hacer TAB con el teclado sobre el documento el links se marcan. Muy molesto cuando tenemos botoneras con imagenes, o imagenes mapeadas, también aplica a anclas que quedan marcadas al darles clic.


Respuesta
Código:
<!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>Un Focus by Nicolás Pardo</title>
<script>
function unFocusA() {
    anclas=document.getElementsByTagName("a").length;
    for (i=0;i<anclas;i++)
    document.getElementsByTagName("a").item(i).onfocus=new Function("if(this.blur)this.blur()")
}</script>
</head>

<body onload="unFocusA()">
<a href="asa.hh">Test link</a>
</body>
</html>
__________________
Mi punto de partida es Que Bueno Lo Nuevo
  #255 (permalink)  
Antiguo 13/05/2007, 07:35
Avatar de nicolaspar  
Fecha de Ingreso: noviembre-2004
Ubicación: Villa Ballester Bs-As|Ar
Mensajes: 2.002
Antigüedad: 19 años, 5 meses
Puntos: 34
Re: FAQs JavaScript

Pregunta: Como avisarle al usuario que tiene un bloqueador de popup?
Respuesta:
Código:
function popup(url,ancho,alto,id,extras){
    if(navigator.userAgent.indexOf("Mac")>0){ancho=parseInt(ancho)+15;alto=parseInt(alto)+15;}
    var left = (screen.availWidth-ancho)/2;
    var top = (screen.availHeight-alto)/2;
    if(extras!=""){extras=","+extras;};
    var ventana = window.open(url,id,'width='+ancho+',height='+alto+',left='+left+',top='+top+',screenX='+left+',screenY='+top+extras);
    var bloqueado = "AVISO:\n\nPara ver este contenido es necesario que desactive\nel Bloqueo de Ventanas para este Sitio."
    //var bloqueado = "WARNING:\n\nIn order to use this functionality, you need\nto deactivate Popup Blocking."
    if(ventana==null || typeof(ventana.document)=="undefined"){ alert(bloqueado) }else{ return ventana; };
}
Notas:
1- Los bloqueadores generalmente trabajan sobre eventos que no son directos del usuario, ejemplo onload, con esto digo que no es necesario para eventos como ser onclick.
2- Hay bloqueadores que lo que hacen es abrir el popup y luego cerrarlo, para ellos esta función no aplica.
__________________
Mi punto de partida es Que Bueno Lo Nuevo
  #256 (permalink)  
Antiguo 13/05/2007, 07:41
Avatar de nicolaspar  
Fecha de Ingreso: noviembre-2004
Ubicación: Villa Ballester Bs-As|Ar
Mensajes: 2.002
Antigüedad: 19 años, 5 meses
Puntos: 34
Re: FAQs JavaScript

Pregunta: Hay algo para que me reemplaze los saltos de lineas por br?
Respuesta:
Código:
function nl2br(text){
    text = escape(text);
    if(text.indexOf('%0D%0A') > -1){
        re_nlchar = /%0D%0A/g ;
    }else if(text.indexOf('%0A') > -1){
        re_nlchar = /%0A/g ;
    }else if(text.indexOf('%0D') > -1){
        re_nlchar = /%0D/g ;
    }
    return unescape( text.replace(re_nlchar,'<br />') );
}
__________________
Mi punto de partida es Que Bueno Lo Nuevo
  #257 (permalink)  
Antiguo 05/06/2007, 09:11
Avatar de stock  
Fecha de Ingreso: junio-2004
Ubicación: Monterrey NL
Mensajes: 2.390
Antigüedad: 19 años, 10 meses
Puntos: 53
Re: FAQs JavaScript

Pregunta: como puedo hacer un carrusel de imagenes?
Respuesta: un carrusel de imagenes, o un slideshow, es muy sencillo de realizar, simplemente necesitas ir sustitullendo las imagenes en contenedores, y luego hacer una transicion, mas explicacion al respecto en el siguiente link:

http://www.crysfel.com/index.php/200...l-de-imagenes/

have funnnnnnnnn
  #258 (permalink)  
Antiguo 06/07/2007, 02:18
 
Fecha de Ingreso: junio-2003
Ubicación: madrid
Mensajes: 342
Antigüedad: 20 años, 10 meses
Puntos: 3
No imprimir ciertas partes de una página.

Pregunta: Como imprimir una página pero no imprimir el menu u otros elemenos.
Respuesta: con este sencillo código indicas lo que no debe ser impreso.

Cita:
<script type="text/javascript">

function removeelements(){
var removeclass="remove"
var alltags=document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==removeclass)
alltags[i].style.display="none"
}
}

function revertback(){
setTimeout("window.location.reload()",50)
}

window.onbeforeprint=removeelements
window.onafterprint=revertback

</script>

<body>
<p class="remove"><img src="bannerad.gif"></p>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<tr>
<td width="20%" class="remove">Left Nav Bar</td>
<td width="80%">Main Content</td>
</tr>
</table>
  #259 (permalink)  
Antiguo 25/07/2007, 16:19
 
Fecha de Ingreso: marzo-2007
Mensajes: 49
Antigüedad: 17 años, 1 mes
Puntos: 0
Validaciones ..

P ¿Cómo puedo validar campos de texto y a la vez un upload?

R

Mucho me ha ayudado este foro, asi que aquí les dejo una validación con Javascript, valida los campos de texto y las extenciones para hacer un upload.


f
Código PHP:
unction valida ()    
    {        
    
    if(
document.form.nombre_usuario.value ==''){
    
alert("Por favor introduzca su nombre.");
    
document.form.nombre_usuario.focus();
    return; }    
    
    if(
document.form.apellidos_usuario.value ==''){
    
alert("Por favor introduzca sus apellidos.");
    
document.form.apellidos_usuario.focus();
    return; }    

    if(
document.form.correo.value == ''){
    
alert("Por favor introduzca su email.");
    
document.form.correo.focus();
    return; }
    
    if ((
document.form.correo.value.indexOf ('@'0) == -1)||(document.form.correo.value.length 5)||(document.form.correo.value.indexOf ('.'6) == -1)){ 
    
alert("Por favor, introduzca una dirección de correo electrónico válida."); 
    
document.form.correo.focus();
    return (
false); }    


//Valida el upload de los archivos para que sólo envíe los archivos con extención requerida 
            
var "false"
var document.getElementById('file').value;
var 
llarg c.length;
var 
extension c.substring(c.length-3,c.length)

    if (
extension == "cvs" || == "") {
    
"true";
     }
    else if (
document.getElementById("file").value.indexOf('.cvs',0)== -1)
    {
    
//document.getElementById("SecondTrack").value.indexOf('.gif',0)== -1){
    
alert("El archivo no tiene una extensión correcta, verifique");
    
document.getElementById("file").select();
    
document.getElementById("file").focus();
    return (
false);
    } 
  #260 (permalink)  
Antiguo 09/10/2007, 04:01
 
Fecha de Ingreso: octubre-2007
Mensajes: 1
Antigüedad: 16 años, 6 meses
Puntos: 1
De acuerdo Re: 37.- text que admita solo numeros

Cita:
Iniciado por atlante Ver Mensaje
P : Como se puede impedir que se ingrese un dato no numerico ?

R :
Código PHP:
<HTML>
<
HEAD>
<
TITLE></TITLE>
</
HEAD>
<
script language="javascript">
<!--
function 
LP_data(){
var 
key=window.event.keyCode;//codigo de tecla.
if (key 48 || key 57){//si no es numero 
window.event.keyCode=0;//anula la entrada de texto.
}}
-->
</script> 
<basefont face=verdana size=2>
<BODY>
<form name="miForm">
<input type=text name="num" onKeypress="LP_data()"><br><br>
<input type="button" value="enviar" onClick="LP_box()">
</form>
</BODY>
</HTML>
hola, este es mi primer post. escribo citando porque no se como es el protocolo. mejore este codigo, y lo posteo aqui para que lo puedan publicar y otras personas puedan usarlo.
la solucion que tienen es solo para internet explorer, sólo acepta numeros del teclado (NO numpad), esta version soluciona eso...

Código PHP:
<html>
<
head>
<
title>valida solo numeros y punto decimal</title>
<
script language="javascript">
function 
filtro(evento) {
var 
keyCode evento.which evento.which evento.keyCode;
var 
valido "1234567890abcdefghi`n¾.";
keychar String.fromCharCode(keyCode); //alert(keychar);
return (valido.indexOf(keychar) != "-1") || keyCode == 8;
/* NOTA:
la variable 'valido' contiene todos los caracteres que corresponden a numeros
sí, numeros!, para ver que caracter es la tecla que presionan, descomenten 'alert(keychar);'
despues, verifico que la tecla que se presione, corresponda a algun caracter de la cadena, si
es asi, entonces se devuelve true y el caracter aparece en el textbox, sino, envio keyCode=8 (backspace) y se borra.
Es verdad que acepta mas de un punto decimal, pero eso ya es algo menor

espero les sea de utilidad

saludos :)
*/
}
</script>
</head>
<body>
<input name="textfield" type="text" id="textfield" onKeyDown="return filtro(event)">
</body>
</html> 
  #261 (permalink)  
Antiguo 10/12/2007, 03:59
Avatar de tunait
Moderadora
 
Fecha de Ingreso: agosto-2001
Ubicación: Terok Nor
Mensajes: 16.805
Antigüedad: 22 años, 8 meses
Puntos: 381
Rotador de banners

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

R.- Este es un mini software gratuito que genera el código javascript necesario para hacer un rotador de banners.

http://gitana2007.blogspot.com/2007/...avascript.html

Se puede hacer una descarga directa desde aquí
http://rapidshare.com/files/72465750...r_1_0_0_11.zip


el codigo JS que genera el soft está publicado en:
http://gitana2007.blogspot.com/2007/...e-banners.html

El soft ha sido desarrollado por TurKa
  #262 (permalink)  
Antiguo 07/01/2008, 11:52
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
Buscar dentro de la página

P: Cómo hacer un buscador que resalte, en el texto de la página, coincidencias con una cadena de búsqueda?

R:

Código:
<!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>BUSCADOR</title>
<script>
String.prototype.preg_quote=function(){
	p= /([:.\+*?[^\]$(){}=!<>|:)])/g;
	return this.replace(p,"\\$1");
}
function buscar(cadena){
	resetear();
    if(!cadena.length)return;
	var info3;
	cadena=cadena.preg_quote();
	var patron=new RegExp(cadena+'(?!\}\})','gim');
	var espacio=/^\s$/;
	var el=document.getElementsByTagName('html')[0].getElementsByTagName('*');
	for(var i=0;i<el.length;i++){
		if(el[i].hasChildNodes && el[i].nodeName.toLowerCase()!='title' && el[i].nodeName.toLowerCase()!='script' && el[i].nodeName.toLowerCase()!='meta' && el[i].nodeName.toLowerCase()!='link' && el[i].nodeName.toLowerCase()!='style'){
			var tt=el[i].childNodes;
			for(var jj in tt){
				if(tt[jj].nodeType==3 && !espacio.test(tt[jj].nodeValue)){
					patron.lastIndex = 0;
					if(info3=patron.exec(tt[jj].nodeValue)){
						tt[jj].nodeValue=tt[jj].nodeValue.replace(patron,'{{'+tt[jj].nodeValue.substr(info3['index'],cadena.length)+'}}');
				
					}
				}

			}		
		}
	}
	document.getElementsByTagName('body')[0].innerHTML=document.getElementsByTagName('body')[0].innerHTML.split('}}').join('</span>').split('{{').join('<span style="background-color: #FFFF99">');
}
function resetear(){
	original=document.getElementsByTagName('body')[0].innerHTML=original;
}
window.onload=function(){
	original=document.getElementsByTagName('body')[0].innerHTML;
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <input name="cadena" type="text" id="cadena" />
  <input type="button" name="Button" value="buscar" onclick="buscar(cadena.value)" />

</form>

ver Buscador simple
<div>sí, dije buscador <div id="pepe">buscador <span> y
      metemos otra vez la palabra buscador} a ver /a qué pasa</span><span>algo
      más </span>y
      esto fuera del span y dentro de div </div>
</div> 
y si ponemos buscador fuera otra vez?
</body>
</html>

Última edición por Panino5001; 07/01/2008 a las 14:17 Razón: sin título
  #263 (permalink)  
Antiguo 21/02/2008, 01:23
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: FAQs JavaScript

P ¿Como muestro un gif animado mientras se carga una imagen o un iframe?
R
Son necesarias 3 cosas... una de ellas es una capa con ese gif animado que en principio esté oculta, un evento que lo muestre que sería un botón o un enlace, y por último el evento de carga del iframe o imagen para volverla a ocultar:
Código:
<html>
<body>
<a onclick="document.getElementById('cargando').style.visibility = 'visible'"
href="http://www.forosdelweb.com" target="destino" >foros del web</a>
<br />
<a onclick="document.getElementById('cargando').style.visibility = 'visible'"
href="http://www.maestrosdelweb.com" target="destino" >maestros del web</a>

<br />
<div style="position: relative" >
<iframe name="destino" style="width: 300px; height: 300px"
onload="document.getElementById('cargando').style.visibility = 'hidden'" ></iframe>
<div id="cargando"
 style="position: absolute; top: 0; left: 0; width: 300px; height: 300px; background: white url(../dibujos/indicator.gif) no-repeat center center; visibility: hidden">
</div>
</body>
</html>
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #264 (permalink)  
Antiguo 15/03/2008, 16:36
 
Fecha de Ingreso: febrero-2008
Mensajes: 20
Antigüedad: 16 años, 2 meses
Puntos: 1
Información Re: 123.- Resta de fechas [corrección un par de errores]

¿Como puedo saber la cantidad de días, meses y años que hay entre dos fechas? --> He encontrado 2 bugs, en el codigo a contiuación el error encontrado y las dos funciónes modificadas.

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);
   }

   
/*Esta función no devuelve bien si el año es bisiesto
   function esBisiesto(nAno){
    var bRes = true;
    res = bRes && (nAno % 4 == 0);
    res = bRes && (nAno % 100 != 0);
    res = bRes || (nAno % 400 == 0);
    return bRes;
   }*/

   /* Esta si funciona bien */
   
function esBisiesto(nAno) {
        return (((
nAno == 0) && (nAno 100 != 0)) || (nAno 400 == 0)) ? true false



   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;
   }

   
/* Tiene un error en 2 fechas con el mismo dia, devolvía 0 dias al pasarle
   dos fechas del mismo dia pero la fecha fin con al mes siguiente que la fecha
   de inicio.
   Ejemplo de bug:
          fecha_inicio: 15/03/2008
          fecha_fin:     15/04/2008
   */
   /*function diasEntre(nDi0, nMe0, nAn0, nDi1, nMe1, nAn1){
    var nRes;
    if (nDi1 < nDi0) nDi1 += finMes(nMe0, nAn0);
    nRes = Math.max(0, nDi1 - nDi0);
    return nRes;
   }*/

   /* Funcion correcta */
   
function diasEntre(nDi0nMe0nAn0nDi1nMe1nAn1) {
       var 
nRes
       if(
nMe0 != nMe1) {
               
nDi1 += 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> 
[/QUOTE]
  #265 (permalink)  
Antiguo 01/04/2008, 01:14
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
FAQ124 - Adjuntar varios ficheros

P: ¿Como puedo adjuntar varios ficheros dinámicamente?

R: Seguro que ya habrá algún mensaje para añadir campos dinámicamente, pero en ocasiones son de difícil validación por el atributo name de los mismos (en explorer no conozco modo de referenciar por ese atributo los campos creados dinámicamente)

El tema se desarrolló en el mensaje: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple file, y el código final sería:

Código:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
	http://www.caricatos.net/probador
</title>
<script>
function tag(id) {return document.getElementById(id)};
var actual = total = 0;
var maximo = 5;
function listar(f)	{
	if (actual == total)	{
		actual = ++total;
		nuevo = document.createElement("div");
		nuevo.onclick = function() {
			tag("file_" + actual).style.display = "none";
			tag("elemento_" + actual).style.backgroundColor = "white";
			actual = this.id.substr(9);
			tag("file_" + actual).style.display = "inline";
			tag("elemento_" + actual).style.backgroundColor = "#eeeeee";
		}
		nuevo.id = "elemento_" + (actual - 1);
		tag("listado").appendChild(nuevo);
		nuevo.appendChild(document.createTextNode(f.value));
		nuevo.style.cursor = "pointer";
		if (total < maximo)	{
			nuevof = f.cloneNode(true);
			f.style.display = "none";
			nuevof['value'] = "";
			nuevof.id = "file_" + actual;
			f.parentNode.insertBefore(nuevof, f.nextSibling);
		}
		else	{
			tag("oculto").style.display = "none";
			actual = 4;
			tag("elemento_" + actual).style.backgroundColor = "#eeeeee";
		}
	}
	else	{
		elem = tag("elemento_" + actual);
		elem.replaceChild(document.createTextNode(f.value), elem.firstChild);
		//tag("elemento_" + actual).innerHTML = f.value;
	}
}
</script>
</head>

<body>
	<form action="javascript: alert('Ok')" >
		<input type="file" onchange="listar(this)" name="userfile[]" id="file_0" size="50" />
		<button type="submit"> enviar </button>
	</form>
	<div id="listado" style="position: relative; background-color: white">
		<div id="oculto" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: transparent">
		</div>
	</div>
</body>
</html>
Se ha añadido un sistema de selección mejorado (con resalte y cursor "pointer")

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #266 (permalink)  
Antiguo 11/04/2008, 04:17
 
Fecha de Ingreso: febrero-2008
Mensajes: 11
Antigüedad: 16 años, 2 meses
Puntos: 0
Re: FAQs JavaScript

P:¿Como puedo validar la direccion de un archivo?

R: Después de mucho busvar y no encontrar una expresión regular para este problema he llegado a la siguiente conclusion:

Cita:
function validaTexto(texto)
{
var
re = /^[-_:\w\.\/\\]+$/i;
if (
!re.test(texto.value)) {
alert (
"Direccion no valida.");
return
false;
}
return
true;
}
Esto valida que la direeción del archivo sea valida (pEj: c:\imagenes\miimagen.jpg) y además no permite que el nombre del archivo tenga caracteres extraños, espacios o acentos que siempre pueden dar problemas.
Tambien sirve para URL.
Puedes usarlo en un formulario como este:
Cita:
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<table width="100%">
<tr>
<td>Insertar Imagen</td>
<td><label>
<input name="imagenes" type="file" id="imagenes" size="60" onblur="validaTexto(this)" />
</label>
</td>
</tr>
<tr>
<td><input type="submit" name="addImg" id="addImg" value="Enviar" /></td>
</tr>
</table>
</form>
  #267 (permalink)  
Antiguo 20/06/2008, 10:53
Avatar de MaBoRaK  
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 2.003
Antigüedad: 21 años
Puntos: 35
Respuesta: FAQs JavaScript

loading.............


P: Como crear variables globales dentro de una funcion
R: Así

Código PHP:
function(){
      
window['mivariableglobal']=23423423432;

connection closed.
__________________

Maborak Technologies
  #268 (permalink)  
Antiguo 20/06/2008, 10:57
Avatar de MaBoRaK  
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 2.003
Antigüedad: 21 años
Puntos: 35
Respuesta: FAQs JavaScript

loading.........


P: Internet Explorer y otros browsers no tiene XMLSerializer
R: A crearlo

Código PHP:
if((typeof XMLSerializer)==='undefined')
                {
                    
window.XMLSerializer = function() {
                        
this.toString=function()
                        {
                            return 
"[object XMLSerializer]";
                        };
                        
this.serializeToString=function(xml){
                            return 
xml.xml || xml.outerHTML || "Error XMLSerializer";
                        };
                    };    
                } 
Muy importante poner

window.XMLSerializer = function()

y no asi
function XMLSerializer()



connection closed.
__________________

Maborak Technologies
  #269 (permalink)  
Antiguo 24/06/2008, 13:36
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
Respuesta: FAQs JavaScript

P: Cómo ajustar el tamaño de un iframe a las dimensiones de la página que contiene:
R:
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></title>
<
script>
function 
getWindowData(n,i){
    var 
ifr=document.getElementById(i).contentWindow.document || document.getElementById(i).contentDocument;
    var 
widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal;
    if (
typeof window.frames[n].innerWidth != 'undefined'){
        
widthViewportwindow.frames[n].innerWidth;
        
heightViewportwindow.frames[n].innerHeight;
    }else if(
typeof ifr.documentElement != 'undefined' && typeof ifr.documentElement.clientWidth !='undefined' && ifr.documentElement.clientWidth != 0){
        
widthViewport=ifr.documentElement.clientWidth;
        
heightViewport=ifr.documentElement.clientHeight;
    }else{
        
widthViewportifr.getElementsByTagName('body')[0].clientWidth;
        
heightViewport=ifr.getElementsByTagName('body')[0].clientHeight;
    }
    
xScroll=window.frames[n].pageXOffset || (ifr.documentElement.scrollLeft+ifr.body.scrollLeft);
    
yScroll=window.frames[n].pageYOffset || (ifr.documentElement.scrollTop+ifr.body.scrollTop);
    
widthTotal=Math.max(ifr.documentElement.scrollWidth,ifr.body.scrollWidth,widthViewport);
    
heightTotal=Math.max(ifr.documentElement.scrollHeight,ifr.body.scrollHeight,heightViewport);
    return [
widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal];

function 
resizeIframe(ID,NOMBRE){
document.getElementById(ID).height=null;
document.getElementById(ID).width=null;
window.location='#';//necesario para safari
var m=getWindowData(NOMBRE,ID); 
document.getElementById(ID).height=m[5];
document.getElementById(ID).width=m[4]+22;

function 
addEvent(objevTypefnuseCapture){
 
 if (
obj.addEventListener){
    
obj.addEventListener(evTypefnuseCapture);
    
  } else if (
obj.attachEvent){
    
obj.attachEvent("on"+evTypefn);
   
  } else {
   
obj['on'+evType]=fn;
  }
}
window.onload=function(){
    
resizeIframe('pp','pp');
    
addEvent(document.getElementById('pp'), 'load', function(){resizeIframe('pp','pp');}, false);
}
</script>
</head>

<body>
<iframe name="pp" id="pp" src="test2.php" frameborder="1" scrolling="no"></iframe></body>
</html> 
(Probado en Safari, Explorer, Ópera y Firefox)

Última edición por Panino5001; 24/06/2008 a las 14:24
  #270 (permalink)  
Antiguo 24/06/2008, 13:47
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 19 años, 10 meses
Puntos: 834
Respuesta: FAQs JavaScript

P: cómo crear un editor WISYWYG sencillo:
R:
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></title>
<
style>
input{
border:1px solid #000;
background:#CCCCCC;
font-family:VerdanaArialHelveticasans-serif;
font-size:9px;
margin-bottom:3px;
}
</
style>
<
script>
var 
editor;
function $(
id){
    return 
document.getElementById(id);
}
function 
formato(f){
    
editor.execCommand(ffalsenull);
}
function 
rev(t)    {
    return 
t.split("<").join("&lt;").split(">").join("&gt;").split("\"").join("&quot;");
}
function 
insertarEnlace(){
    var 
u;
    if(!(
u=prompt('ingresar url','http://')))return;
    
editor.execCommand("CreateLink",false,u);
}
function 
insertarImagen(){
    var 
u;
    if(!(
u=prompt('ingresar url','http://')))return;
    
editor.execCommand("InsertImage",false,u);
}
function 
color(c){
    
editor.execCommand("forecolor",false,c);
}

function 
colorFondo(c){
    var 
h=window.ActiveXObject?'backcolor':'hilitecolor';
    
editor.execCommand(h,false,c);
}
function 
inHTML(){
    var 
u,u2;
    if(!(
u=prompt('ingresar html')))return;
    
        try{
            
editor.execCommand("inserthtml",false,u);
        }catch(
e){
            try{
                
u2=editor.selection.createRange();
                
u2.pasteHTML(u);
            }catch(
E){
                
alert('nop');
            }
        }
}

function 
htmlOEditor(e){
e=|| window.event;
ob=e.target || e.srcElement
$('edit').style.display=(ob.value=='html')?'none':'block';
$(
'ht').style.display=(ob.value!='html')?'none':'block';
$(
'ht').innerHTML=rev(editor.body.innerHTML);
ob.value=(ob.value=='html')?'editor':'html';
}
window.onload=function(){
    
    
editor=$('edit').contentDocument || $('edit').contentWindow.document;
    
editor.designMode='on';
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <input type="button" name="Submit" value="N" onclick="formato('bold')" />
  <input type="button" name="Submit2" value="C" onclick="formato('italic')" />
  <input type="button" name="Submit3" value="S" onclick="formato('underline')" />
  <input type="button" name="Submit4" value="remover formato" onclick="formato('RemoveFormat')" />
  <input type="button" name="Submit5" value="link" onclick="insertarEnlace()" />
  <input type="button" name="Submit9" value="quitar link" onclick="formato('Unlink')" />
  <input type="button" name="Submit6" value="imagen" onclick="insertarImagen()" />
  <input type="button" name="Submit7" value="texto rojo" onclick="color('#FF0000')" />
  <input type="button" name="Submit8" value="fondo rojo" onclick="colorFondo('#FF0000')" />
    <input type="button" name="Submit10" value="deshacer" onclick="formato('undo')" />
  <input type="button" name="Submit11" value="rehacer" onclick="formato('redo')" />

  <input type="button" name="Submit12" value="insertar html" onclick="inHTML()" />
  <br />
<iframe id="edit" width="100%" height="300" style=" border:1px solid #000;"></iframe>
<div id="ht" style="width:100%; height:300px; overflow:auto; border:1px solid #000; display:none"></div>
<div style="margin-top:3px;"><input name="ver" type="button" id="ver" onclick="htmlOEditor(event)" value="html" /></div>
</form>
</body>
</html> 
(Probado en Safari, Explorer, Ópera y Firefox)
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 04:53.