Javascript Get Selected Text / Copy Selected Text

Javascript Get Selected Text

<script language=javascript>
function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection) // FireFox
    {
        txt = document.getSelection();
            }
    else if (document.selection)  // IE 6/7
    {
        txt = document.selection.createRange().text;
            }
    else return;
document.aform.selectedtext.value =  txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()">
<form name=aform >
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>

 

Posted by:

Comments History


by: on
I've tested above with Firefox and IE, works like a charm to copy selected text.
 
by: on
Simple Example (IE): exeCommand Hey try to Copy some of my code here and press button next to me
 
by: on
i have tested the above code, it works fine for IE 7 but not working for Mozila(version 3.0).can u help me.
 
by: on
Can you post your Code?
 
by: on
function getSelText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); } else if (document.getSelection) { txt = document.getSelection(); alert('txt:'+txt); } else if (document.selection) { txt = document.selection.createRange().text; document.getElementById('lblMessage5').focus(); var sel=document.selection.createRange(); } if(txt != '') { alert('txt:'+txt); var hidden_control=''; hidden_control=document.getElementById('Textdrag'); hidden_control.value=txt; insertslistTag(); } }
 
by: on
I will test your code tomorrow.
 
by: on
error: 'setting a property that has only a getter' Any solution to this error? FF5.0
 
by: on
This solution is incomplete. What is returned is not necessarily a string. On FF3 I get an object for txt, so basic things I want to do, like testing length, does not work. Best to do: txt = txt.toString(); if you want uniform results before using them.
 
by: on
I use the Following Code, works great.:
 
by: on
Nice snippet. I was wondering if any one was aware of a way to use this in connection with an iFrame that has external content in it ? I had tried: $("#iframeElement")[0].contentDocument.document.getSelection(); which is essentially document.getElementById(iframeId).contentDocument.document.getSelection(); both of which give the following error: Permission denied for to get property HTMLDocument.document from Any ideas would be intensely helpful
 
by: on
Your iFrame is populated with a external website (not the same domain?) then its a permission error, you can only select content which is hosted within your own local envirnoment.
 
by: on
I am trying to get the document.getSelection() to work when I selected text within a




 

 

| Android app on Google Play |