We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

jamesming on 09/15/08


Tagged

textarea


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

m00min
sulfurito


How to replace selected textarea value using javascript


Published in: JavaScript 


URL: http://corpocrat.com/2008/08/10/how-to-get-selected-value-in-textarea-using-javascript/

  1. // code for IE
  2. var textarea = document.getElementById("textarea");
  3.  
  4. if (document.selection)
  5. {
  6. textarea.focus();
  7. var sel = document.selection.createRange();
  8. // alert the selected text in textarea
  9. alert(sel.text);
  10.  
  11. // Finally replace the value of the selected text with this new replacement one
  12. sel.text = '<b>' + sel.text + '</b>';
  13. }
  14.  
  15.  
  16.  
  17.  
  18. // code for Mozilla
  19.  
  20. var textarea = document.getElementById("textarea");
  21.  
  22. var len = textarea.value.length;
  23. var start = textarea.selectionStart;
  24. var end = textarea.selectionEnd;
  25. var sel = textarea.value.substring(start, end);
  26.  
  27. // This is the selected text and alert it
  28. alert(sel);
  29.  
  30. var replace = '<b>' + sel + '<b>';
  31.  
  32. // Here we are replacing the selected text with this one
  33. textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);

Report this snippet 

You need to login to post a comment.