How do I do a "select all" and "copy to clipboard" with Javascript for an asp:label?
14,295
Updated
The following will highlight the desired div and then copy the HTML to the clipboard. Go to Word and press CTRL+V to paste the formatted html into a document.
<script type="text/javascript">
function CopyHTMLToClipboard() {
if (document.body.createControlRange) {
var htmlContent = document.getElementById('MainContent_lblHtml');
var controlRange;
var range = document.body.createTextRange();
range.moveToElementText(htmlContent);
//Uncomment the next line if you don't want the text in the div to be selected
range.select();
controlRange = document.body.createControlRange();
controlRange.addElement(htmlContent);
//This line will copy the formatted text to the clipboard
controlRange.execCommand('Copy');
alert('Your HTML has been copied\n\r\n\rGo to Word and press Ctrl+V');
}
}
</script>
Author by
Ben
Updated on June 04, 2022Comments
-
Ben almost 2 years
I want to copy the content of an asp:label using javascript.
I can do it using this method:
strContent = document.getElementById('MainContent_lblHtml').innerText; window.clipboardData.setData("Text", strContent);
but it strips the formatting and just copies text. (I assume because the dataformat is set to "text".)
The label contains some formatted html. I want to preserve the format, getting the same effect as if I were to highlight it on screen with my mouse, and then copy into (for example) a word document.
-
Ben about 13 yearsStill not quite what I'm after. You'll have to forgive my ignorance, as I'm not quite sure how it works. If you paste a website contents into Word it'll retain the formatting. If you paste via innerHTML as above it'll put the tags into Word.
-
NakedBrunch about 13 yearsAh, I see. I thought you only wanted to copy the HTML itself. I've updated the code so that copying will allow you to paste fully formatted code into a Microsoft Word document.
-
Ben about 13 yearsThanks VERY much! This was driving me crazy!
-
NakedBrunch about 13 yearsGreat. It was driving me crazy too. It took me a while to figure out.
-
Admin over 12 years"Uncomment the next line if you don't want the text in the div to be selected" should be "Uncomment the next line if you DO want the text in the div to be selected"