August 10th in Javascript by pbu .

how to get selected textarea value using javascript

how to get the selected value in textbox and change its value? how to do it in javascript?

This is what i am after. I was working on a bbcode editor and i wanted to get the the selected text in the textarea and wanted to insert bbcode tags in place of them. I needed just very simple javascript code an finally i found a solution working in both IE and Firefox.

// code for IE
var textarea = document.getElementById("textarea");

if (document.selection)
			{
				textarea.focus();
				var sel = document.selection.createRange();
                                // alert the selected text in textarea
				alert(sel.text);

                               // Finally replace the value of the selected text with this new replacement one
				sel.text = '<b>' + sel.text + '</b>';
			}

The above code only works in IE versions. You will need a different javascript code that works in Firefox. The document.selection will be true if it is IE else it would return false.

In Mozilla, you have to first get the length, starting point of cursor and ending point of highlighted cursor. While doing replacement you have first output the textarea value from substr(0,Startingpoint) + replacement + substr(Startingpoint,Length). This is the trick to change or replace the selected text in the textarea.

// code for Mozilla

  var textarea = document.getElementById("textarea");

  var len = textarea.value.length;
   var start = textarea.selectionStart;
   var end = textarea.selectionEnd;
   var sel = textarea.value.substring(start, end);

   // This is the selected text and alert it
   alert(sel);

  var replace = '<b>' + sel + '<b>';

  // Here we are replacing the selected text with this one
 textarea.value =  textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);

Just thought that i could share my little work in my blog.

Similar Posts:

Share and Enjoy:
  • del.icio.us
  • digg
  • StumbleUpon
  • Technorati
  • DZone
  • Facebook
  • FriendFeed
  • Reddit
  • RSS
  • Twitter

4 Comments

  • pqm
    November 5, 2008
  • pbu
    November 5, 2008
  • Amina Rabeck
    January 6, 2010
  • Ganzorig
    March 12, 2010

Leave A Comment.