¿Eres nuevo? ¡Lee el FAQ y ponte al día!
2k visitas

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
  1. // Gets the selection in a textfield
  2. function getSelection(myField)
  3. {
  4.     //IE support
  5.     if (document.selection)
  6.     {
  7.         myField.focus();
  8.         sel = document.selection.createRange();
  9.         return sel.text;
  10.     }
  11.     //MOZILLA/NETSCAPE support
  12.     else if (myField.selectionStart || myField.selectionStart == "0")
  13.     {
  14.         var startPos = myField.selectionStart;
  15.         var endPos = myField.selectionEnd;
  16.  
  17.         return myField.value.substr(startPos, endPos - startPos);
  18.     } else {
  19.         return "";
  20.     }
  21. }
  22.  

­

Etiquetas: JavaScript textarea

Insertar: