I have two <textarea>
s. One with id="input"
and the other with id="selection"
.
<textarea id="input">
will contain some HTML. The user will select some text in this textarea, click a button and the selected text will be copied to <textarea id="selection">
.
I can use jQuery or just vanilla JavaScript and I'd like it to work in IE7+, Safari and Firefox.
I have two <textarea>
s. One with id="input"
and the other with id="selection"
.
<textarea id="input">
will contain some HTML. The user will select some text in this textarea, click a button and the selected text will be copied to <textarea id="selection">
.
I can use jQuery or just vanilla JavaScript and I'd like it to work in IE7+, Safari and Firefox.
Share Improve this question edited Jul 14, 2012 at 21:57 random 9,95510 gold badges69 silver badges84 bronze badges asked Dec 3, 2010 at 3:33 joeljoeljoeljoeljoeljoel 6331 gold badge6 silver badges8 bronze badges3 Answers
Reset to default 7There'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./post/92274686/highlight-selected-text-with-jquery
The following will do it:
See it in action: http://www.jsfiddle/QenBV/1/
function getSelectedText(el) {
if (typeof el.selectionStart == "number") {
return el.value.slice(el.selectionStart, el.selectionEnd);
} else if (typeof document.selection != "undefined") {
var range = document.selection.createRange();
if (range.parentElement() == el) {
return range.text;
}
}
return "";
}
function copySelected() {
var srcTextarea = document.getElementById("input");
var destTextarea = document.getElementById("selection");
destTextarea.value = getSelectedText(srcTextarea);
}
<input type="button" onclick="copySelected()" value="copy selected">
with jquery you can do as below
$('#selection').val($('#input').val());
http://api.jquery./val/