2010-10-19 40 views
12

¿cuál es la mejor manera de hacer esto en jQuery? Este debería ser un caso de uso bastante común.Reemplazar el texto seleccionado en el área de texto

  1. El usuario selecciona texto en un área de texto
  2. Hace clic en un enlace
  3. El texto en el enlace sustituye el texto seleccionado en el área de texto

Cualquier código será muy apreciada - Soy Tiene algunos problemas con la parte 3.

+0

Las propiedades '' selectionStart' y selectionEnd' de su '' textarea' o input' es todo lo que necesita hoy en día. Combine eso con el método 'slice' en el valor del elemento de entrada. – caw

Respuesta

16

Así es cómo puede hacerlo, en todos los navegadores principales. También tengo un jQuery plug-in que incluye esta funcionalidad. Con esto, el código sería

$("your_textarea_id").replaceSelectedText("NEW TEXT"); 

Aquí hay una solución independiente completo:

function getInputSelection(el) { 
    var start = 0, end = 0, normalizedValue, range, 
     textInputRange, len, endRange; 

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { 
     start = el.selectionStart; 
     end = el.selectionEnd; 
    } else { 
     range = document.selection.createRange(); 

     if (range && range.parentElement() == el) { 
      len = el.value.length; 
      normalizedValue = el.value.replace(/\r\n/g, "\n"); 

      // Create a working TextRange that lives only in the input 
      textInputRange = el.createTextRange(); 
      textInputRange.moveToBookmark(range.getBookmark()); 

      // Check if the start and end of the selection are at the very end 
      // of the input, since moveStart/moveEnd doesn't return what we want 
      // in those cases 
      endRange = el.createTextRange(); 
      endRange.collapse(false); 

      if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { 
       start = end = len; 
      } else { 
       start = -textInputRange.moveStart("character", -len); 
       start += normalizedValue.slice(0, start).split("\n").length - 1; 

       if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) { 
        end = len; 
       } else { 
        end = -textInputRange.moveEnd("character", -len); 
        end += normalizedValue.slice(0, end).split("\n").length - 1; 
       } 
      } 
     } 
    } 

    return { 
     start: start, 
     end: end 
    }; 
} 

function replaceSelectedText(el, text) { 
    var sel = getInputSelection(el), val = el.value; 
    el.value = val.slice(0, sel.start) + text + val.slice(sel.end); 
} 

var el = document.getElementById("your_textarea"); 
replaceSelectedText(el, "[NEW TEXT]"); 
+0

Este será un plugin increíblemente útil. Muchas gracias! Es un poco extraño cómo este caso de uso aún no está cubierto. Traté de escribir el mío, pero acerté con tantas peculiaridades del navegador. ;) –

+0

replaceSelectedText - el único problema que veo con esto es que en IE, cuando no se selecciona nada, el cursor va al frente, en lugar de al final. de todos modos que se puede arreglar? –

+0

¿En el código publicado aquí o en el plugin jQuery? El código aquí no hace ningún intento de reposicionar la selección después, por el bien de la brevedad. El plugin jQuery debería lidiar con eso. –

Cuestiones relacionadas