Foros del Web » Programando para Internet » Javascript »

borrar enlace

Estas en el tema de borrar enlace en el foro de Javascript en Foros del Web. hola a todos, tengo un problema con una funcion. lo que quiero hacer es sobre un texto crear dos botones para insertar y borrar un ...
  #1 (permalink)  
Antiguo 25/01/2008, 15:02
 
Fecha de Ingreso: octubre-2007
Mensajes: 24
Antigüedad: 16 años, 6 meses
Puntos: 0
borrar enlace

hola a todos,

tengo un problema con una funcion. lo que quiero hacer es sobre un texto crear dos botones para insertar y borrar un enlace.
el boton de insertar lo tengo ya y funciona perfectamente, el problema viene con el de borrar.
os dejo el codigo por si alguien puede ayudarme

function init(){
incluidos=init.arguments;
for(i=0;i<incluidos.length;i++){
var cuerpo=document.body.innerHTML;
html="<table align="center" width="750"><tr><td valign="top"> <input type="button" value="INSERTAR ENLACE" onclick="inslink('"+incluidos[i]+"')" > </td></tr></table><table align="center" width="750"><textarea name=""+incluidos[i]+"" cols="90" rows="10" id=""+incluidos[i]+"">";
pat="<textarea+[^>]*"+incluidos[i]+"+[^<]+";
patron =new RegExp(pat,"gi");
coincidencias=new Array();
coincidencias=cuerpo.match(patron);
for(j=0;j<coincidencias.length;j++){
result=new Array();
result=coincidencias[j].match(/s+id=[^>s]+/g);
result[0]=result[0].split('"').join('');
result[0]=result[0].split('id=').join('');
result[0]=result[0].split(' ').join('');
if(result[0]==incluidos[i]){
valor=new Array();
valor2='';
valor=coincidencias[j].split('>');
if(valor.length>1){
for(k=1;k<valor.length;k++){
valor2+=valor[k];
}
}
cuerpo2=cuerpo.split(coincidencias[j]);
}
}

document.body.innerHTML=cuerpo2[0]+html+valor2+cuerpo2[1];
}
}

function inslink(campo){
var input = document.getElementById(campo);
if(typeof document.selection != 'undefined' && document.selection) {
var str = document.selection.createRange().text;
input.focus();
var my_link = prompt("Introduzca la URL:","http://");
if (my_link != null) {
if(str.length==0){
str=my_link;
}
var sel = document.selection.createRange();
sel.text = "<a href="" + my_link + "" target="_blank" class="link">" + str + "</a>";
sel.select();
}
return;
}else if(typeof input.selectionStart != 'undefined'){
if(typeof input.scrollTop != 'undefined'){
var st=input.scrollTop;
var sl=input.scrollTop;
}
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 +"" target="_blank" class="link">" + insText + "</a>"+ input.value.substr(end);
input.focus();
if(typeof input.scrollTop != 'undefined'){
input.scrollTop=st;
input.scrollTop=sl;
}
input.setSelectionRange(start+11+my_link.length+in sText.length+4,start+11+my_link.length+insText.len gth+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;
}
}
  #2 (permalink)  
Antiguo 26/01/2008, 13:35
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Re: borrar enlace

Más o menos así:
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>test</title>
<script>
campo='ejemplo';
function quitarenlace(){
	var input = document.getElementById(campo);
	var patern= /^\s*<a\b[^>]*>(.*?)<\/a>\s*$/;
	if(typeof document.selection != 'undefined' && document.selection) {
		var str = document.selection.createRange().text;
		input.focus();
		var sel = document.selection.createRange();
		if(!patern.test(sel.text)){throw 'error al seleccionar el enlace';return;}
		sel.text = sel.text.split('>')[1].split('<')[0];
		sel.select();
		
		return;
	}else if(typeof input.selectionStart != 'undefined'){
		if(typeof input.scrollTop != 'undefined'){
			var st=input.scrollTop;
			var sl=input.scrollTop;
		}
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var insText = input.value.substring(start, end);
		
		if(!patern.test(insText)){throw 'error al seleccionar el enlace';return;}
		insText=insText.split('>')[1].split('<')[0];;
		input.value = input.value.substr(0, start) +insText+ input.value.substr(end);
		input.focus();
		if(typeof input.scrollTop != 'undefined'){
			input.scrollTop=st;
			input.scrollTop=sl;
		}

		return;
	}else{
		return;
	}
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <textarea name="ejemplo" cols="60" rows="5" id="ejemplo">otra cosa &lt;a href=&quot;http://www.google.com&quot;&gt;lo que sea &lt;/a&gt; otra cosaotra cosa &lt;a href=&quot;http://www.google.com&quot;&gt;lo que sea &lt;/a&gt; otra cosa</textarea>
  <input type="button" name="Submit" value="quitar enlace" onclick="try{quitarenlace();}catch(e){alert(e)}" />
</form>
</body>
</html>
  #3 (permalink)  
Antiguo 26/01/2008, 14:44
 
Fecha de Ingreso: octubre-2007
Mensajes: 24
Antigüedad: 16 años, 6 meses
Puntos: 0
Re: borrar enlace

Panino eres un crack, te lo digo de verdad, me has ayudado muchisimo.
Gracias, gracias y mil veces gracias
  #4 (permalink)  
Antiguo 26/01/2008, 15:30
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Re: borrar enlace

Me alegra que te sirva. Igualmente, no bien pueda intentaré mejorarlo
Edito: Aquí esta una versión algo mejorada:
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>test</title>
<script>
campo='ejemplo';
String.prototype.substr_count = function() 
{
  var search = arguments[0];
  var count = 0;
  var pos = this.indexOf(search);
  while ( pos != -1 ) {
     count++;
     pos = this.indexOf(search,pos+1);
  }
  return count;
} 
function quitarenlace(){
	var input = document.getElementById(campo);
	var patern= /^\s*<a\b[^>]*>(.*?)<\/a>\s*$/;
	if(typeof document.selection != 'undefined' && document.selection) {
		var str = document.selection.createRange().text;
		input.focus();
		var sel = document.selection.createRange();
		if(!patern.test(sel.text) || sel.text.substr_count('</a>')>1 || sel.text.substr_count('<a')>1){throw 'error al seleccionar el enlace';return;}
		sel.text = sel.text.split('>')[1].split('<')[0];
		sel.select();
		
		return;
	}else if(typeof input.selectionStart != 'undefined'){
		if(typeof input.scrollTop != 'undefined'){
			var st=input.scrollTop;
			var sl=input.scrollTop;
		}
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var insText = input.value.substring(start, end);
		
		if(!patern.test(insText)|| insText.substr_count('</a>')>1 || insText.substr_count('<a')>1){throw 'error al seleccionar el enlace';return;}
		insText=insText.split('>')[1].split('<')[0];
		input.value = input.value.substr(0, start) +insText+ input.value.substr(end);
		input.focus();
		if(typeof input.scrollTop != 'undefined'){
			input.scrollTop=st;
			input.scrollTop=sl;
		}

		return;
	}else{
		return;
	}
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <textarea name="ejemplo" cols="60" rows="5" id="ejemplo">otra cosa &lt;a href=&quot;http://www.google.com&quot;&gt;lo que sea &lt;/a&gt; otra cosaotra cosa &lt;a href=&quot;http://www.google.com&quot;&gt;lo que sea &lt;/a&gt; otra cosa</textarea>
  <input type="button" name="Submit" value="quitar enlace" onclick="try{quitarenlace();}catch(e){alert(e)}" />
</form>
</body>
</html>

Última edición por Panino5001; 26/01/2008 a las 20:20
  #5 (permalink)  
Antiguo 27/01/2008, 14:16
 
Fecha de Ingreso: octubre-2007
Mensajes: 24
Antigüedad: 16 años, 6 meses
Puntos: 0
Re: borrar enlace

muchas gracias,

pero tengo un pequeño problema y es que este formulario lo añado mediante
<script src="../bbcode/bbcode.js"></script>
<body onLoad="init('txttexto')">
dentro de otro formulario en el que al final hay un boton de "Enviar" y en firefox no me funciona, deberia enviar a la bd toda la informacion que introduzco en los campos del formulario y no es asi, ¿sabes a que se debe?
  #6 (permalink)  
Antiguo 27/01/2008, 14:37
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Re: borrar enlace

Imposible decirlo sin verlo. Subí la página a algún lugar donde pueda verse y lo miro.
  #7 (permalink)  
Antiguo 27/01/2008, 14:54
 
Fecha de Ingreso: octubre-2007
Mensajes: 24
Antigüedad: 16 años, 6 meses
Puntos: 0
Re: borrar enlace

Mira el código es el siguiente:

Código:
<? } 

if($_GET["procesar"]=="OK"){

	$titular= $_POST["txttitular"];
	$fecha= $_POST["txtfecha"];
	$texto= $_POST["txttexto"];
	
	if($_GET["op"]=="EDIT"){
	
		$sql="UPDATE mociones SET  titular='$titular',fecha='$fecha',texto='$texto' where id_mociones=".$_GET["mocion"];
		mysql_query($sql,$dbcon);
		
			
	}	
			
		
	if($_GET["op"]=="NEW"){		
		
		$sql="insert into mociones(titular,fecha,texto)values('$titular','$fecha','$texto')";
		mysql_query($sql,$dbcon);
	
	}

}

if($_GET["op"]=="EDIT"){
	$sql="select * from mociones where id_mociones=". $_GET["mocion"];
	$resultado=mysql_query($sql,$dbcon);
	
	while($registro= mysql_fetch_array($resultado)){ 
	$idmociones=$registro["id_mociones"];
	$titular=$registro["titular"];
	$fecha=$registro["fecha"];
	$texto=$registro["texto"];
	}
}		




?>
<!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>:: CREAR UNA NUEVA MOCIÓN ::</title>
<link href="css/cue.css" rel="stylesheet" type="text/css" />
</head>
<script src="../bbcode/bbcode.js"></script>
<body onLoad="init('txttexto')"><table width="750" border="0" cellspacing="0" cellpadding="0" align="center">
  <tr>
    <td><img src="../img/nueva_mocion.gif" /></td>
  </tr>
</table>

<br /><br />
<table width="750" border="0" cellspacing="0" cellpadding="0" align="center">
<form action="../adm/formulario_mociones.php?procesar=OK&op=<?=$_GET["op"]?>&mocion=<?=$_GET["mocion"]?>" method="post" enctype="multipart/form-data" >
  <tr>
    <td class="formulariocontacto">Titular:</td>
  </tr>
  <tr>
    <td><input name="txttitular" value="<?=$titular?>" type="text" size="120" class="brevefechatexto"/></td>
  </tr>
  <tr><td height="20"></td></tr>
  <tr>
    <td class="formulariocontacto">Fecha:</td>
  </tr>
  <tr>
    <td><input name="txtfecha"  value="<?=$fecha?>" type="text" width="200" size="120" class="brevefechatexto"/></td>
  </tr>
  <tr><td height="20"></td></tr>
  <tr>
    <td class="formulariocontacto">Texto:</td>
  </tr>
  <tr>
    <td class="brevefechatexto">
<textarea name="txttexto" cols="140" rows="10" id="txttexto"  class="brevefechatexto" ><?=$texto?></textarea></td>
  </tr>
  <tr><td height="20"></td></tr>
  <tr><td height="20"></td></tr>
  <tr>
        <td height="40"><input type="Submit" value="Enviar"/></td></tr>
	<tr><td height="40"><a href="privado/privada.php" class="volver">Volver al menú principal</a></td></tr>
	<tr><td height="40"><input name="button" type="button" onClick="window.close();" value="Cerrar el administrador" />  
</form>

</table>


</body>
</html>
y el bbcode es este:

Código:
function init(){
	incluidos=init.arguments;
	for(i=0;i<incluidos.length;i++){
		var cuerpo=document.body.innerHTML;
		html="<table align=\"center\" width=\"750\"><tr><td valign=\"top\"> <input type=\"button\"  value=\"INSERTAR ENLACE\" onclick=\"inslink('"+incluidos[i]+"')\"  >&nbsp;<input type=\"button\"  value=\"BORRAR ENLACE\" onclick=\"try{borrarlink();}catch(e){alert(e)}\">&nbsp;</td></tr></table><table align=\"center\" width=\"750\"><textarea name=\""+incluidos[i]+"\" cols=\"122\" rows=\"10\" id=\""+incluidos[i]+"\" class=\"brevefechatexto\">";
		pat="<textarea+[^>]*"+incluidos[i]+"+[^<]+"; 	
		patron =new RegExp(pat,"gi");
		coincidencias=new Array();
		coincidencias=cuerpo.match(patron);
		for(j=0;j<coincidencias.length;j++){
			result=new Array();
			result=coincidencias[j].match(/\s+id=[^>\s]+/g);
			result[0]=result[0].split('"').join(''); 
			result[0]=result[0].split('id=').join(''); 
			result[0]=result[0].split(' ').join(''); 
			if(result[0]==incluidos[i]){
				valor=new Array();
				valor2='';
				valor=coincidencias[j].split('>');
				if(valor.length>1){
						for(k=1;k<valor.length;k++){
							valor2+=valor[k];
						}
					}
				cuerpo2=cuerpo.split(coincidencias[j]);
			}
		}
		
		document.body.innerHTML=cuerpo2[0]+html+valor2+cuerpo2[1];
	}
}

function inslink(campo){
	var input = document.getElementById(campo);
		if(typeof document.selection != 'undefined' && document.selection) {
			var str = document.selection.createRange().text;
			input.focus();
			var my_link = prompt("Introduzca la URL:","http://");
				if (my_link != null) {
					if(str.length==0){
						str=my_link;
					}
					var sel = document.selection.createRange();
					sel.text = "<a href=\"" + my_link + "\" target=\"_blank\" class=\"link\">" + str + "</a>";
					sel.select();
					}
			return;
		}else if(typeof input.selectionStart != 'undefined'){
				if(typeof input.scrollTop != 'undefined'){
					var st=input.scrollTop;
					var sl=input.scrollTop;
				}		
					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 +"\" target=\"_blank\" class=\"link\">" + insText  + "</a>"+ input.value.substr(end);
							input.focus();
							if(typeof input.scrollTop != 'undefined'){
								input.scrollTop=st;
								input.scrollTop=sl;
							}
							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;
		}
}
campo='txttexto';
String.prototype.substr_count = function() 
{
  var search = arguments[0];
  var count = 0;
  var pos = this.indexOf(search);
  while ( pos != -1 ) {
     count++;
     pos = this.indexOf(search,pos+1);
  }
  return count;
} 
function borrarlink(){
	var input = document.getElementById(campo);
	var patern= /^\s*<a\b[^>]*>(.*?)<\/a>\s*$/;
	if(typeof document.selection != 'undefined' && document.selection) {
		var str = document.selection.createRange().text;
		input.focus();
		var sel = document.selection.createRange();
		if(!patern.test(sel.text) || sel.text.substr_count('</a>')>1 || sel.text.substr_count('<a')>1){throw 'error al seleccionar el enlace';return;}
		sel.text = sel.text.split('>')[1].split('<')[0];
		sel.select();
		
		return;
	}else if(typeof input.selectionStart != 'undefined'){
		if(typeof input.scrollTop != 'undefined'){
			var st=input.scrollTop;
			var sl=input.scrollTop;
		}
		var start = input.selectionStart;
		var end = input.selectionEnd;
		var insText = input.value.substring(start, end);
		
		if(!patern.test(insText)|| insText.substr_count('</a>')>1 || insText.substr_count('<a')>1){throw 'error al seleccionar el enlace';return;}
		insText=insText.split('>')[1].split('<')[0];
		input.value = input.value.substr(0, start) +insText+ input.value.substr(end);
		input.focus();
		if(typeof input.scrollTop != 'undefined'){
			input.scrollTop=st;
			input.scrollTop=sl;
		}

		return;
	}else{
		return;
	}
}
lo que ocurre es que cuando en firefox yo pulso el boton de enviar no pasa nada en cambio en explorer funciona (cosa muy curiosa)
  #8 (permalink)  
Antiguo 27/01/2008, 20:54
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Re: borrar enlace

Habría que verlo funcionando en algún lado. A mi el formulario se me envía sin problemas. Una cosa que te sugiero es formatear con htmlentities el texto del textarea, que es a lo que seguramente se debe tu problema:
Código PHP:
<?=htmlentities($texto)?>

Última edición por Panino5001; 27/01/2008 a las 21:09
  #9 (permalink)  
Antiguo 28/01/2008, 03:18
 
Fecha de Ingreso: octubre-2007
Mensajes: 24
Antigüedad: 16 años, 6 meses
Puntos: 0
Re: borrar enlace

Lo puedes ver aquí: http://www.cuelkb-estellalizarra.org/adm/formulario_mociones.php.

Luego tengo un par de dudas más. ¿Cómo puedo hacer para que explorer no me bloquee la ventana de la url cuando pulso insertar enlace?. He probado a cambiar la configuración del bloqueador de elementos emergentes y sigue bloqueandolo.
Y ¿cómo puedo hacer para que en el textarea "txttexto" se vea el enlace que se inserta con el estilo css que le aplico y no esto "aaaa<a href="http://" target="_blank" class="link">enlace</a>"?. es decir que desaparezca la etiqueta a href.

Gracias
  #10 (permalink)  
Antiguo 28/01/2008, 11:03
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Re: borrar enlace

Problema de html:
Tenés esto:
Código PHP:
<table><form>...</form></table
Cambialo por:
Código PHP:
<form><table>...</table></form
Y solucionarás el problema.
  #11 (permalink)  
Antiguo 29/01/2008, 03:16
 
Fecha de Ingreso: octubre-2007
Mensajes: 24
Antigüedad: 16 años, 6 meses
Puntos: 0
Re: borrar enlace

Vaya, muchas gracias Panino, ni me había dado cuenta.

Muchisimas gracias por toda tu ayuda
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:08.