September 14, 2011

.getSelection()

Question by Jean

HTML code–

<script language="javascript" type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<script language="javascript" type="text/javascript" src="js/jquery.field.selection.js"></script>

    <div id="copy">Copy</div>
        <textarea....id="t">

jquery—

$(docu.....
$('#copy').click(function(){
var range = $('#TextArea').getSelection();
alert(range.text);
});

});

When the #copy button is pressed the alert does not show the selected text in #t. It comes in blank.

I need the selected text from the textarea

Answer by Starx

Your code is not running because, this statement fails

var range = $('#TextArea').getSelection();

There is nothing as TextArea as ID in the markup you provided, so the script encounters an error and does not continue beyond it.

If you place the alert at the top part, I am sure the alert box will pop up.
i.e

$('#copy').click(function(){
    alert(''); //this will work
    var range = $('#TextArea').getSelection();
    alert(range.text);
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!