1

In a simple webapp, I have a text area with some text, when user highligh a word in the text area, then click a button to process the word, the handler failed to get the highlighted word.

<input type="button" value="click" onclick="handle()"><input>
<textarea> </textarea>
<script>
function handle() {
alert(window.getSelection().toString());
}
</script> 

Any idea how to do this?
Thanks

UPDATE1

When I run window.getSelection().toString() in Chrome developer console, it does give the highlighted text, however, when I click a button. it returned nothing. I guess clicking will de-highlight the highlighted text.

packetie
  • 4,839
  • 8
  • 37
  • 72
  • Try [this](http://stackoverflow.com/questions/717224/how-to-get-selected-text-in-textarea) and [this](http://stackoverflow.com/questions/1058048/how-to-get-selected-text-inside-a-textarea-element-by-javascript) – galactocalypse Jul 11 '15 at 19:08
  • Thanks @galactocalypse for the links. Just updated my question, the issue seems to be, clicking the button will de-highlight the text, defeating the purpose. – packetie Jul 11 '15 at 19:12
  • Even with the de-highlight, the selection remains selected. You should get the values anyway. I just tried this on FF and it worked. – galactocalypse Jul 11 '15 at 19:23
  • When I tried it on my Chrome, `window.getSelection()` when lose its value when clicking another button, but I `textareaObj.selectionStart, textareaObj.selectionEnd` will retain the value when clicking on a button. So I came up with a solution using it. Thanks again for trying and the good info that it works fine on FF. – packetie Jul 11 '15 at 21:46

2 Answers2

0

Clicking the button as you say will deselect the text. One work around could be this:

  1. Bind a mouseup up event and store the highlited if there is. Here is some reference: Selected text event trigger in Javascript

  2. When you click the button you can use the stored text.

Right now I'm on my phone, but when I get access to a pc I can provide some code.

Here is some reference also for preventing the highlited text to be lost: Any way to prevent "deselection" of highlighted text?

Community
  • 1
  • 1
Alvaro Flaño Larrondo
  • 5,516
  • 2
  • 27
  • 46
-2

Maybe try this -

window.(textareaID).getselection().tostring

Create textareaID:

<textarea id="*your id here*><\textarea>