2k views
Obtener el texto seleccionado en un textarea
Esta es una función muy básica para conseguir el texto seleccionado en un textarea. Se podría mejorar añadiendo algunas comprobaciones más, pero este código se usa aquí, en The Source Cookbook, y parece funcionar bastante bien.
Javascript
- // Gets the selection in a textfield
- function getSelection(myField)
- {
- //IE support
- if (document.selection)
- {
- myField.focus();
- sel = document.selection.createRange();
- return sel.text;
- }
- //MOZILLA/NETSCAPE support
- else if (myField.selectionStart || myField.selectionStart == "0")
- {
- var startPos = myField.selectionStart;
- var endPos = myField.selectionEnd;
- return myField.value.substr(startPos, endPos - startPos);
- } else {
- return "";
- }
- }
Submitted by miguelSantirso over 2 years ago — last modified less than a minute ago