How to replace selected textarea value using javascript


/ Published in: JavaScript



Copy this code and paste it in your HTML
  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);

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.