tags:

views:

164

answers:

2

I'm trying to read in the value of selected text within a text area. Here is my code:

function readSelected(id)
{ 
    textarea = document.getElementById(id);
    if (document.selection)
    { //Code for IE
        textarea.focus();
        sel = document.selection.createRange();
        alert(sel.text);
    }
    else 
    {  // Code for Mozilla Firefox
        var len = textarea.value.length;
        var start = textarea.selectionStart;
        var end = textarea.selectionEnd;

        var scrollTop = textarea.scrollTop;
        var scrollLeft = textarea.scrollLeft;

        sel = textarea.value.substring(start, end);

        alert(sel);
    }
}

HTML:

<textarea id="txt1" rows="10"></textarea> 
<a onclick="readSelected('txt1');">Get Selected</a>

When you click the button, a popup should occur telling you what the selected text is.

The code works in Firefox, but I can't get it to work in IE8.

A: 

The problem is that clicking on the <a> element destroys the selection. You could use an unselectable button instead:

<input type="button" value="get" onclick="readSelected('txt1');" unselectable>

There are other minor issues with your code

  1. You should declare all your variables, otherwise they end up leaking into the global scope. sel and textarea are the offenders here.
  2. scrollTop and scrollLeft are redundant.
  3. You should test for the selectionStart and selectionEnd properties first, since they're the standard (HTML 5 specifies them and IE 9 will support them).

Here's my rewritten version:

function readSelected(id) {
    var sel = "", el = document.getElementById(id);
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        sel = el.value.slice(el.selectionStart, el.selectionEnd);
    } else if (document.selection && document.selection.createRange) {
        el.focus();
        sel = document.selection.createRange().text;
    }
    alert(sel);
}
Tim Down
Thanks for the response. The code corrections are appreciated! Is there any reason to not use onmousedown as the other answerer suggested, assuming I make the neccesary JS corrections as you have suggested?
Morgan
None that I can see.
Tim Down
A: 

Did you try with onmousedown instead of onclick ?

Fabien Ménager
It works with `onmousedown`. Is there any reason to use onclick vs onmousedown; other than that it works? I'm not opposed to changing the `<a>` to `<input>`, as Tim suggested.
Morgan
`onmousedown` if fired before the "deselection" of the text that occurs when the mouse is released.
Fabien Ménager