Thursday, November 27, 2008

Get the selected text using Javascript

Sometimes you want to know what text the user has selected with their mouse. The below function is used to get the selected text into text area. Place the follwoing code in the head section of html

function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else
return;
document.aform.selectedtext.value = txt;
}


call this function in the button click event or where ever you want.

<input type="button" value="Get selection" onmousedown="getSelText()"><form name=aform ><textarea name="selectedtext" rows="5" cols="20"></textarea>



No comments:

Post a Comment