Solved

Retrieve selected data from text area.

Posted on 2008-06-24
27
1,311 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
Comment Utility
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
Comment Utility
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
Comment Utility
0
 

Assisted Solution

by:yerzu
yerzu earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
@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
Comment Utility
@scrathcyboy

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

Expert Comment

by:scrathcyboy
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
No...my textarea was not empty Gary.
0
 

Expert Comment

by:yerzu
Comment Utility
change onSelect to onClick ... now its work good in IE7:)
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 1

Expert Comment

by:GaryRasmussen
Comment Utility
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
Comment Utility
I'll try it again but that is not the behavior I got with IE7.
0
 
LVL 1

Expert Comment

by:GaryRasmussen
Comment Utility
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
Comment Utility
The fruits of your labor.

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

Expert Comment

by:GaryRasmussen
Comment Utility
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
Comment Utility
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
Comment Utility
|| is a logical operator OR
=== this is small mistake, should be ==, change it!;)
0
 
LVL 1

Expert Comment

by:GaryRasmussen
Comment Utility
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
Comment Utility
I must have copied it wrong into my test page, but it does work cross-browser.
0
 
LVL 1

Expert Comment

by:GaryRasmussen
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …

772 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now