PrintLogo

Capturing Selected Text with JavaScript




Here is a way to capture text that is selected within a textarea box. As with this article, I have only included what is necessary for the script to function on a recent browser like IE or Mozilla/Firefox. For an example of how to do this outside a textarea box with even more stringent browser requirements, see this article.

Here is the version for a textarea box:


Select your city from the text above, or type in your own city, and click the place button below.


Here is the source code for the above:

<script language="JavaScript">
function display(txtarea){
var sl = (txtarea.value).substring(txtarea.selectionStart,
txtarea.selectionEnd);  
prompt ("The place you have selected is:",sl);
} 
</script>
<body bgcolor="white"  onload="thisForm=document.frmKey;">
<form method="POST" action="art466.html" id="frmTest" name="frmKey">
<textarea name="entry" rows="10" cols="70">Dallas, got a soft machine. 
Houston, too close to New Orleans.
New York's got the ways and means, but just won't let you be, oh no.</textarea>
<br />
Select your city, and click the place button below.<br />
<img onClick="display(thisForm.entry);" src="images/place.gif">
</form>

For more on the textarea tag, see this reference. For a great doc on this and other JavaScript selection methods, see this. Of particular interest, here, is that you can select any text on the page with later versions of Mozilla and the window.getSelection() function.

For the complete program that uses this, see this article.



This article comes from NetAdminTools:
http://www.netadmintools.com/

The URL for this story is:
http://www.netadmintools.com/art466.html

Copyright 1997-2007 NetAdminTools.com. Read our Terms of Use.