There's only one way I've been able to do it. The problem you're running into, as you may be aware, is that when you click the button (thus firing the event to copy the selection), the textarea loses focus, and thereby there's no text selected.
So as a workaround, I styled a div to look (kinda) like a textarea. That seems to work:
<style type="text/css">
.textarea {
border:1px solid black;
width:200px;
height:100px;
overflow-y: auto;
float:left;
}
</style>
The markup then looks like this:
<div id="input" class="textarea">This is a test</div>
<textarea id="selection"></textarea>
<button id="theButton">Copy</button>
And finally, the script:
var selText = "";
$( document ).ready( function() {
$( '#theButton' ).mousedown( function() {
$( '#selection' ).val( getSelectedText() );
});
});
function getSelectedText(){
if ( window.getSelection ) {
return window.getSelection().toString();
}
else if ( document.getSelection ) {
return document.getSelection();
} else if ( document.selection ) {
return document.selection.createRange().text;
}
}
To give full credit where it's due, I got the getSelectedText() method from http://esbueno.noahstokes.com/post/92274686/highlight-selected-text-with-jquery