简体   繁体   中英

Get highlighted text from div and copy into textarea javascript

Managed to get highlighted text from within a textarea and transfer it into another textarea. But when the code is edited so that it gets the highlighted text from within a div instead, it does not work...

Any ideas why this is happening? Thanks.

<div id="quote"> load transcript in here instead and grab text from here</div> // does not work

<textarea id="quote" readonly> // works
load transcript in here
</textarea>


<textarea contenteditable="false" id="output" name="selected"></textarea> // outputs highlighted text here


<script>

var quotearea = document.getElementById('quote')
var output = document.getElementById('output')
quotearea.addEventListener('mouseup', function(){
    if (this.selectionStart != this.selectionEnd){ // check the user has selected some text inside field
        var selectedtext = this.value.substring(this.selectionStart, this.selectionEnd)
        output.innerHTML = selectedtext
    }
}, false)

</script>

fiddle:

https://jsfiddle.net/Lzgyh2kd/

I answered your question in the comments and deleted it.

You're using selectionStart and selectionEnd methods that works only on input elements. For your solution used instead document.selection.createRange().text that gets the selected text in the document (inputs, divs, etc., doesn't matter).

Here's the fiddle:

Working demo

Someone in the comments answered it with a fiddle that had two textarea, but edited one to a div and it seems to work. Cheers. (Edit- turns out a div was not required, it took straight from the page, so a workaround)

<div name="" id="original">
Load transcript in here.
</div>

<textarea name="" id="copied" cols="30" rows="10"></textarea>

<script>


var text = '';
function copyText(e) {
    text = (document.all) ? document.selection.createRange().text : document.getSelection();
    document.getElementById('copied').value = text;
}
document.onmouseup = copyText;
if (!document.all) {
    document.captureEvents(Event.MOUSEUP);
}


</script>

Working fiddle here:

https://jsfiddle.net/eLwy4eLp/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM