Thursday, August 19, 2010

How to replace selected textarea value using javascript

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

  23. textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);

1 comment:

  1. Very wonderful and informative piece of content you have shared. To learn more about Java from beginning and make career as a programmer, get enroll at Online Java Course in Kolkata, Delhi. Noida, Alwar, Pune and in many other cities of India.

    ReplyDelete

5 Strategies for Getting More Work Done in Less Time

Summary.    You’ve got more to do than could possibly get done with your current work style. You’ve prioritized. You’ve planned. You’ve dele...