
mavera
Tengo un cuadro de texto y un botón de enlace. Cuando escribo algún texto, selecciono algo y luego hago clic en el botón de enlace, el texto seleccionado del cuadro de texto debe mostrarse con un cuadro de mensaje.
¿Cómo puedo hacerlo?
Cuando hago clic en el botón Enviar para el cuadro de texto a continuación, el cuadro de mensaje debe mostrar lorem ipsum. Porque “Lorem ipsum” está seleccionado en el área.
Si selecciono cualquier texto de la página y hago clic en el botón Enviar, funciona, pero si escribo un texto en el cuadro de texto y lo hago, no funciona. Porque cuando hago clic en otro espacio, la selección del cuadro de texto se cancela.
Ahora el problema es que, cuando selecciono texto del cuadro de texto y hago clic en cualquier otro control o espacio, el texto que está seleccionado aún debe estar seleccionado.
¿Como se hace?

Filho
OK, aquí está el código que tengo:
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{ // Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
El problema es que, aunque el código que doy para Internet Explorer está en muchos sitios, no puedo hacer que funcione en mi copia de explorador de Internet 6 en mi sistema actual. Tal vez te funcione, y por eso te lo doy.
El truco que busca es probablemente la llamada .focus() para devolver el foco al área de texto, por lo que la selección se reactiva.
Obtuve el resultado correcto (el contenido de la selección) con el onKeyDown evento:
document.onkeydown = function (e) { ShowSelection(); }
Entonces el código es correcto. Nuevamente, el problema es obtener la selección al hacer clic en un botón… Continúo buscando.
No tuve ningún éxito con un botón dibujado con un li
etiqueta, porque cuando hacemos clic en ella, Internet Explorer deselecciona la selección anterior. El código anterior funciona con un simple input
botón, sin embargo…

Dan Dascalescu
Aquí hay una solución mucho más simple, basada en el hecho de que la selección de texto ocurre al subir el mouse, por lo que agregamos un detector de eventos para eso:
document.querySelector('textarea').addEventListener('mouseup', function () {
window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
// window.getSelection().toString();
});
<textarea>
Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>
Esto funciona en todos los navegadores.
Si también desea manejar la selección a través del teclado, agregue otro detector de eventos para keyup
con el mismo código.
Si no fuera por este error de Firefox presentado en 2001 (sí, hace 14 años), podríamos reemplazar el valor asignado a window.mySelection
con window.getSelection().toString()
que funciona en IE9+ y todos los navegadores modernos, y también obtiene la selección realizada en partes del DOM que no son áreas de texto.

prat3ik-patel
function disp() {
var text = document.getElementById("text");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
alert
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />

sombra2531
Para Opera, Firefox y Safari, puede utilizar la siguiente función:
function getTextFieldSelection(textField) {
return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}
Luego, simplemente pasa una referencia a un elemento de campo de texto (como un área de texto o un elemento de entrada) a la función:
alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));
O, si desea que
HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
var ss = this.selectionStart;
var se = this.selectionEnd;
if (typeof ss === "number" && typeof se === "number") {
return this.value.substring(this.selectionStart, this.selectionEnd);
}
return "";
};
Entonces, simplemente harías:
alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());
por ejemplo.

pescadojd
soy un gran aficionado de jQuery-textrange.
A continuación se muestra un ejemplo muy pequeño e independiente. Descargar jquery-textrange.js y copiarlo en la misma carpeta.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery-textrange</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery-textrange.js"></script>
<script>
/* Run on document load */
$(document).ready(function() {
/* Run on any change of 'textarea' **/
$('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {
/* The magic is on this line **/
var range = $(this).textrange();
/* Stuff into selectedId. I wanted to
store this is a input field so it
can be submitted in a form. */
$('#selectedId').val(range.text);
});
});
</script>
</head>
<body>
The smallest example possible using
<a href="https://github.com/dwieeb/jquery-textrange">
jquery-textrange
</a><br/>
<textarea id="textareaId">Some random content.</textarea><br/>
<input type="text" id="selectedId"></input>
</body>
</html>

Pedro Mortensen
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);
// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);
Creo que debería mirar las propiedades de inicio/fin de selección del campo de entrada para firefox y textrange en IE alguna referencia: http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/
– MatthieuGD
9 de noviembre de 2008 a las 9:34