Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

aletres

[Resolvido] Firefox não retorna seleção de input com Javascipt

Recommended Posts

A seleção parece funcionar mas ele não recebe/retorna a string. No IE funciona. Qual a diferença para o Firefox?

 

<script language="JavaScript">
function FormatarTexto(campo,tipo)
{
	//Verifica se o Objeto existe
	if(document.getElementById(campo)) {
		//Atribui foco ao objeto
		document.getElementById(campo).focus();
		//Recupera Texto Selecionado
		var strTexto = document.selection.createRange().text;
		//Verifica se variável contém algum valor
		if(strTexto.length > 0) {
			//Verifica se o texto já está negritado (verificação básica)
			if(strTexto.substring(0,3) != "<" + tipo + ">") {
				// Negrita o texto selecionado
				document.selection.createRange().text = "<" + tipo + ">" + strTexto + "</" + tipo +">";
			}
		}
	}
}
</script>

<a href="#" onClick="FormatarTexto('campo_texto','b');">Negrito</a>

Desde já agradeço.

Alexandre

Compartilhar este post


Link para o post
Compartilhar em outros sites

Utilizei e continua não funcionando apenas no Firefox:

 

<script language="JavaScript">
function FormatarTexto(campo,tipo) {
	var textArea = document.getElementById(campo);
	if (document.selection) { //IE
		textArea.selectedText = document.selection.createRange().text;
		textArea.selectionStart = textArea.value.indexOf(textArea.selectedText);
		textArea.selectionEnd = textArea.selectionStart + textArea.selectedText.length;
		if (textArea.selectionStart < 0) {
			textArea.selectionStart = 0;
			textArea.selectionEnd = 0;
		}
	} else if (textArea.selectionStart){ 
		textArea.selectedText = textArea.substring(textArea.selectionStart,textArea.selectionEnd);
	}
	document.selection.createRange().text = "<" + tipo + ">" + textArea.selectedText + "</" + tipo +">";
	alert("Selection Start==> " + textArea.selectionStart + "\n" +
	"Selection End  ==> " + textArea.selectionEnd + "\n" +
	"Selected Text  ==> " + textArea.selectedText + "\n" +
	"TextArea Value ==> " + textArea.value);
}
</script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Exemplo do que você quer:

<html>
	<head>
		<title>Exemplo</title>
		<script type="text/JavaScript">
				adicionaEvento(window, 'load', function(){
					adicionaEvento(document.getElementsByName("b1")[0], 'click', function(){
						var txC = document.getElementsByName("txq")[0];
						var selectedText = "";
						if(txC.selectionStart){
							selectedText = txC.value.substring(txC.selectionStart, txC.selectionEnd);
						} else if(document.selection){
							var range = document.selection.createRange();
							if(range.parentNode == txC) selectedText = range.text;
						}
						if(selectedText != "") document.getElementById("res").innerHTML = "Texto selecionado:" + selectedText;
					}, false);
				}, false);

			function adicionaEvento(elemento, evento, funcao, bool){
			bool = (bool == null)? false : bool;
			if(elemento.addEventListener)
				elemento.addEventListener(evento, funcao, bool);
				else
					elemento.attachEvent('on' + evento, funcao);
			}

		</script>
	</head>
	<body>
		 Texto qualquer:<input type="text" name="txq" /><br />
		 <input type="button" value="Pegar texto selecionado" name="b1" />
		 <div id="res">Texto selecionado:</div>
	</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Valeu pela força galera mas o meu problema está na seguinte linha:

 

document.selection.createRange().text = "<" + tipo + ">" + textArea.selectedText + "</" + tipo +">";

Eu não consigo enviar a variável de volta para o capo texto pelo document.selection.createRange().text.

 

Há alguma outra forma no FF?

 

Valeu!

Compartilhar este post


Link para o post
Compartilhar em outros sites

O que você quer no firefox seria algo como(exemplo):

<html>
	<head>
		<title>Exemplo</title>
		<script type="text/JavaScript">
				adicionaEvento(window, 'load', function(){
					adicionaEvento(document.getElementsByName("b1")[0], 'click', function(){
						var txC = document.getElementsByName("txq")[0];
						var selectedText = "";
						if(txC.selectionStart){
							selectedText = txC.value.substring(txC.selectionStart, txC.selectionEnd);
							txC.value = txC.value.substring(0, txC.selectionStart) + "<algo>" + selectedText + "</algo>" + txC.value.substring(txC.selectionEnd-1, txC.value.length-1);
						} else if(document.selection){
							var range = document.selection.createRange();
							if(range.parentNode == txC){
								selectedText = range.text;
								range.text = "<algo>" + selectedText + "</algo>";
							}
						}
					}, false);
				}, false);

			function adicionaEvento(elemento, evento, funcao, bool){
			bool = (bool == null)? false : bool;
			if(elemento.addEventListener)
				elemento.addEventListener(evento, funcao, bool);
				else
					elemento.attachEvent('on' + evento, funcao);
			}

		</script>
	</head>
	<body>
		 Texto qualquer:<input type="text" name="txq" /><br />
		 <input type="button" value="Pegar texto selecionado" name="b1" />
	</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá pessoal!

 

Depois de "debulhar" o código do Eibon e ver que algumas coisas não funcionavam e outras resultavam em algo incorreto, cheguei em uma conclusão:

 

<html>
	<head>
		<title>Exemplo</title>
<script type="text/JavaScript">
function FormatarTexto(campo,tipo) {
	var txtCopia = document.getElementsByName(campo)[0];
	var selectedText = "";
	selectedText = txtCopia.value.substring(txtCopia.selectionStart, txtCopia.selectionEnd);
	if(txtCopia.selectionStart){ // FF
		txtCopia.value = txtCopia.value.substring(0, txtCopia.selectionStart) + "<" + tipo + ">" + selectedText + "</" + tipo + ">" + txtCopia.value.substring(txtCopia.selectionEnd, txtCopia.value.length);
	} else if(document.selection){ // IE
		var rangeIE = document.selection.createRange();
		selectedText = rangeIE.text;
		if(selectedText){
			rangeIE.text = "<" + tipo + ">" + selectedText + "</" + tipo + ">";
		}
	}
}
</script>
	</head>
	<body>
	<p>Texto qualquer:<br>
	  <input type="text" name="noticia_texto" />
	</p>
	<p><strong><a href="#" onClick="FormatarTexto('noticia_texto','b');">ENVIAR</a></strong></p>
	</body>
</html>

A princípio funciona corretamente no FF 3.0 e no IE 8.0. Porém...

 

Há duas coisinhas que não funcionaram:

 

1. Quando se seleciona algo a partir do 1º caracter não há retorno (pelo FF);

2. Quando não é selecionado algo no campo, o mesmo não retorna as tags para o campo correspondente (pelo IE);

 

O que mais preocupa é a 1ª questão. Alguém sabe dizer o que é?

 

Um abraço e obrigado a todos que ajudaram a resolver este mistério [:)]

 

Alexandre.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Correção:

<html>
	<head>
		<title>Exemplo</title>
		<script type="text/JavaScript">
				adicionaEvento(window, 'load', function(){
					adicionaEvento(document.getElementsByName("b1")[0], 'click', function(){
						var txC = document.getElementsByName("txq")[0];
						var selectedText = "";
						if(txC.selectionEnd){
							selectedText = txC.value.substring(txC.selectionStart, txC.selectionEnd);
							txC.value = txC.value.substring(0, txC.selectionStart) + "<algo>" + selectedText + "</algo>" + txC.value.substring(txC.selectionEnd-1, txC.value.length-1);
						} else if(document.selection){
							var range = document.selection.createRange();
							if(range.parentNode == txC){
								selectedText = range.text;
								if(selectedText != "") range.text = "<algo>" + selectedText + "</algo>";
							}
						}
					}, false);
				}, false);

			function adicionaEvento(elemento, evento, funcao, bool){
			bool = (bool == null)? false : bool;
			if(elemento.addEventListener)
				elemento.addEventListener(evento, funcao, bool);
				else
					elemento.attachEvent('on' + evento, funcao);
			}

		</script>
	</head>
	<body>
		 Texto qualquer:<input type="text" name="txq" /><br />
		 <input type="button" value="Pegar texto selecionado" name="b1" />
	</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Eibon, não sei porque mas os códigos que você manda não funcionam corretamente em nenhum dos dois navegadores. Qual você usa?

 

Mesmo assim agradeço a ajuda, SEUS CÓDIGOS AJUDARAM BASTANTE e estou a um passo de resolver o problema, só falta esse lançe do FF saber quando escolho a partir do 1º caracter (não sei pq mas ele não reconhece).

 

Achei um código que funcionou muito bem, depois vou estuda-lo melhor para entende-lo pois achei muito complexo (mas pelo menos funciona):

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Exemplo de uso da função selection</title>
<script type="text/javascript">
<!--

function selection(obj, set_text_default){
	if(obj.constructor == String){obj = document.getElementById(obj);}
	var set_text = (set_text_default) ? function(text){obj.value += text;} : function(){return false;};
	var selection = {text: "", setText: set_text};
	if(document.selection){
		var range = document.selection.createRange();
		if(range.text){
			selection.text = range.text;
			selection.setText = function(text){
				range.text = text.replace(/\r?\n/g, "\r\n");
			}
	}
	} else if(typeof(obj.selectionStart) != "undefined"){
		selection.text = obj.value.substring(obj.selectionStart, obj.selectionEnd);
		selection.setText = function(text){
			obj.value = obj.value.substring(0, obj.selectionStart) + text + obj.value.substring(obj.selectionEnd);
		}
	} else if(window.getSelection){
		selection.text = window.getSelection().toString();
	}
	return selection;
}


function wrapText(obj, before, after){
	var selected = selection(obj, true);
	selected.setText(before + selected.text + after);
}

//-->
</script>
</head>
<body>
<textarea id="text"></textarea>
<p>
	<button onclick="wrapText('text', '<strong>', '</strong>')">strong</button>
	<button onclick="wrapText('text', '<em>', '</em>')">em</button>
	<button onclick="wrapText('text', '<u>', '</u>')">u</button>
</p>
</body>
</html>

Você consegue ver como ele resolveu a questão do selectionStart no primeiro caracter?

 

Obrigado por tudo!

 

Alexandre.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Testei minha correção,e tinha funcionado perfeitamente no Opera e no Firefox.

Anyway...que bom que resolveu seu problema.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.