Solved

Retrieve selected data from text area.

Posted on 2008-06-24
27
1,313 Views
Last Modified: 2011-10-19
I have a form with a textarea containing say 30 words.

If I select one or more consecutive words via left click and draggin the mouse to highlight those words in can use the onmouseup event to fire a JavaScript function.

I would like that function to obtain only the selected words into a JavaScript variable.
text-select.txt
0
Comment
Question by:rdivilbiss
  • 10
  • 9
  • 4
  • +1
27 Comments
 
LVL 1

Accepted Solution

by:
GaryRasmussen earned 250 total points
ID: 21861475
Here ya go

<html>
<head>
<title></title>
<script language=javascript>
function Init()
{      var box = document.getElementById("txtWrite")
      
      box.onmouseup = MouseUp
      if (box.captureEvents)
      {      box.captureEvents(Event.MOUSEUP)
      }
}

function MouseUp(e)      
{      if (!e) var e = window.event

      var box = (e.srcElement) ? e.srcElement : e.target
      var selText = GetSelectedText(box)
      alert (selText)
}


function GetSelectedText(input)
{      if (document.selection && document.selection.createRange().text != '')
      {      return (document.selection.createRange().text)
      }
      else
      {      var startPos = input.selectionStart
            var endPos = input.selectionEnd;
            return input.value.substring(startPos, endPos)
      }
}
</script>
</head>
<body onload="Init()">
<form ID="Form1">
<textarea id="txtWrite" rows="20" cols="20"></textarea>
</form>
</body>
</html>
0
 
LVL 44

Expert Comment

by:scrathcyboy
ID: 21861533
I think you will find the code for Mozilla and Firefox is different than for IE, so you might consider the code below, also checking for Mozilla as well as firefox (I hate pages that assume that firefox is the only Mozilla like browser.  Mozilla and Netscape existed long before firefox and still Mozilla beats FF for rendering) --
function getSelecetedTextarea(){ 
var isFF = false; 
var textselected = false; 
if(navigator.userAgent.toLowerCase().indexOf("firefox") > 0){ 
isFF = true; 
} 
var myArea = document.getElementById("body"); 
var begin,selection,end; 
if (isFF == true){ 
if (myArea.selectionStart!= undefined) {  
begin = myArea.value.substr(0, myArea.selectionStart);  
selection = myArea.value.substr(myArea.selectionStart, myArea.selectionEnd - myArea.selectionStart);  
end = myArea.value.substr(myArea.selectionEnd); 
if (selection.length > 0){ 
textselected = true; 
} 
} 
}else{ 
if (window.getSelection){ 
selection = window.getSelection(); 
}else if (document.getSelection){ 
selection = document.getSelection(); 
}else if (document.selection){ 
selection = document.selection.createRange().text; 
} 
var startPos = myArea.value.indexOf(selection); 
if (startPos!= 0){ 
var endPos = myArea.value.indexOf(selection) + selection.length; 
begin = myArea.value.substr(0,startPos); 
end = myArea.value.substr(endPos, myArea.value.length); 
textselected = true; 
} 
} 
if(textselected == true){ 
switch (t){ 
case "code": 
startTag = "[xcode]"; 
endTag = "[/xcode]\n"; 
break; 
 
case "bold":
startTag = "[xb]";
endTag = "[/xb]";
break;
 
case "italics":
startTag = "[xi]";
endTag = "[/xi]";
break;
 
case "link":
startTag = "[xlink url=#*$!#*$!]";
endTag = "[/xlink]";
break;
}
myArea.value = begin + startTag + selection + endTag + end;
myArea.focus();
}else{
alert("No text selected.\nNo tags added");
}
}

Open in new window

0
 
LVL 44

Expert Comment

by:scrathcyboy
ID: 21861557
0
Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 

Assisted Solution

by:yerzu
yerzu earned 250 total points
ID: 21861627
i have better solution:

<html lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Text Select</title>
<script type="text/javascript">
<!--
function getSelectedText(txt,t){
txt.focus()
if(document.selection){
t=document.selection.createRange().text
} else if(txt.selectionStart||txt.selectionStart===0){
t=txt.value.substring(txt.selectionStart|0,txt.selectionEnd|0)
}
alert(t)
}
//-->
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="null">
  <textarea id="txt" name="txt" rows="5"  cols="50"  onSelect="getSelectedText(document.getElementById('txt'))">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras dolor. Sed sed neque. Duis eros justo, bibendum in, placerat eget, ullamcorper vel, nibh. Praesent urna arcu, sagittis eget, semper laoreet, tempus non, augue. In a pede. Vestibulum consequat eleifend sem. Duis tristique tortor ultricies massa. Duis sapien eros, posuere sit amet, rhoncus non, venenatis bibendum, tellus. Donec dui tortor, dignissim quis, eleifend eget, fermentum a, massa. Maecenas vel enim vitae sapien condimentum eleifend. Duis hendrerit luctus dui.</textarea>
</form>
</body>

</html>
0
 
LVL 44

Expert Comment

by:scrathcyboy
ID: 21861683
I think you will find the createRange is IE specific and doesn't work right on the other browsers.  Sorry.
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21861839
scrathcyboy

I saw that example on the internet this morning when I was looking for something similar.  I believe the user in that case was trying to add formatting tags to selected text.  This person is asking for a solution to grab the selected text in a textarea onmouseup of that textarea.  My solution does exactly that for IE and FF.

Perhaps you can take the code I posted and only change the part that makes it work for mozilla so that he gets a complete solution and then it will be there for future searches?  I think all you would have to do is tweak the GetSelectedText() function slightly.

Thanks!
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21862046
@yerzu and GaryRasmussen

On IE7 your version only allows me to select one letter before it fires.

FYI...testing the other one now.
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21862084
@scrathcyboy

I get nothing in any browser.  Care to supply the whole working page?
0
 
LVL 44

Expert Comment

by:scrathcyboy
ID: 21862127
try the links I gave, there are lots more, with lots of divergent information.  I can give you a general link if you want, but I am sure you can do this too....
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21862277
That is because the textarea is empty.  You said that you wanted the script it to fire onmouseup so if the textarea is empty and you click in it to start typing, the mouseup evfent fires.  I modified the MouseUp function to allow you to enter the textarea and start typing if it is blank.  Let me know if I am not understanding you correctly.

function MouseUp(e)      
{      if (!e) var e = window.event
      var box = (e.srcElement) ? e.srcElement : e.target
      if (box.value == "")
      {      return
      }
      var selText = GetSelectedText(box)
    alert (selText)
}
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21862287
Actually yerzu's is the simplest and works cross-browser if I change the event to onlosecapture.  Thank you everybody for looking at this.
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21862484
No...my textarea was not empty Gary.
0
 

Expert Comment

by:yerzu
ID: 21863871
change onSelect to onClick ... now its work good in IE7:)
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21866738
I tested my solution in IE7 and FF 2 and it works exactly as you asked.  you left mouse click and while holding the mouse button down, you drag to the right selecting some text.  When you mouseup to stop selecting, all the selected text is is saved to a variable to do what you want.  Isn't that exactly what you asked for?  I'm confused.
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21866860
I'll try it again but that is not the behavior I got with IE7.
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21867017
I don't get it.  I just tested my code again and now the select function is not working correctly.  I must have had my test page cached and then changed it somehow before submitting it.  Nevermind, I would go with yerzu.  Thanks, and sorry about the mix up.
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21867284
The fruits of your labor.

http://www.rodsdot.com/ee/text_select3.asp
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21867411
You need to change it to the following.  And the points should be split between myself and yerzu.  If you click in the text area and mouseup without selecting anything, then it thinks everything in the textarea was selected.  The following works perfectly.


<html>
<head>
<title></title>
<script language=javascript>
function Init()
{      var box = document.getElementById("txtWrite")
     
      box.onmouseup = MouseUp
      if (box.captureEvents)
      {      box.captureEvents(Event.MOUSEUP)
      }
}

function MouseUp(e)      
{      if (!e) var e = window.event

      var box = (e.srcElement) ? e.srcElement : e.target
      var selText = GetSelectedText()
      if (selText != "")
      {      alert(selText)
      }
}

function GetSelectedText()
{      if (document.selection)
      {      return (document.selection.createRange().text)
      }
      else if (txt.selectionStart || txt.selectionStart === 0)
      {      return (txt.value.substring (txt.selectionStart|0,txt.selectionEnd|0))
      }
}


</script>
</head>
<body onload="Init()">
<form ID="Form1">
<textarea id="txtWrite" rows="20" cols="20" NAME="txtWrite"></textarea>
</form>
</body>
</html>
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21867462
yerzu,

Can you explain this syntax?
 else if (txt.selectionStart || txt.selectionStart === 0)
      {      return (txt.value.substring (txt.selectionStart|0,txt.selectionEnd|0))

I have never seen the use of === or the |

Thanks!
0
 

Expert Comment

by:yerzu
ID: 21867940
|| is a logical operator OR
=== this is small mistake, should be ==, change it!;)
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21868715
yerzu, thanks.  yes, I know what || is but how is the single bar it working in ...
txt.value.substring (txt.selectionStart|0,txt.selectionEnd|0)

0
 
LVL 29

Author Closing Comment

by:rdivilbiss
ID: 31470405
I must have copied it wrong into my test page, but it does work cross-browser.
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21869934
rdivilbiss

Did you see the comment about the === ?

In the GetSelectedText() function, make sure you change === to ==

Thanks!
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21870052
Thanks everybody.  I put youo as contributors on the tutorial page which is answering another Q here, so you answered part of another Q.

This is what I'm using.

<script language=javascript>
function Init() {
      var box = document.getElementById("txtWrite")
      box.onmouseup = MouseUp
      if (box.captureEvents){
            box.captureEvents(Event.MOUSEUP)
      }
}

function MouseUp(e) {
      if (!e) {
            var e = window.event;
      }
      var box = (e.srcElement) ? e.srcElement : e.target
      var selText = GetSelectedText(box)
      if (selText!='') {
            document.getElementById('hlText').value=selText;
      }      
}

function GetSelectedText(input)      {
      //if (document.selection && document.selection.createRange().text != '')      {
      if (document.selection)      {
            return (document.selection.createRange().text)
      } else {
            var startPos = input.selectionStart;
            var endPos = input.selectionEnd;
            return input.value.substring(startPos, endPos);
      }
}
</script>
0
 
LVL 1

Expert Comment

by:GaryRasmussen
ID: 21870112
rdivilbiss,

you are posting the old code that has an issue.  Please use the code posted here at ID 21867411

And then change the GetSelectedText() function, change === to ==
0
 

Expert Comment

by:yerzu
ID: 21870311
this is also OR, x|y if x OR y value is 1 then return 1 in bit type not logical - this is different with || :)
main difference between bit operators and logical operators are prioritis of values in variables, its clear?:)
0
 
LVL 29

Author Comment

by:rdivilbiss
ID: 21870891
Gary,

The code I'm posting works, cross-browser.

This:

else if (txt.selectionStart || txt.selectionStart == 0)
      {      return (txt.value.substring (txt.selectionStart|0,txt.selectionEnd|0))
      }

breaks FF compatibility on my page.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question