Reputation: 3
I'm trying to copy the text of an element on my aspx website and can't get it to work.
I want to click a button and let it copy the text of my lblFileLink to the clipboard.
notice: this page is using a masterpage
here is my code:
<asp:Label ID="lblFileLink" runat="server"></asp:Label>
<asp:Button ID="btnCopy" runat="server" Text="Copy link" OnClientClick="copyToClipboard()" />
<script>
function copyToClipboard() {
var element = document.getElementById("lblFileLink")
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
return false
}
</script>
I want it to do that before postback so with javascrip/jquery
Edit: I noticed the id was different on the site itself so now my code is this:
<asp:Label ID="lblFileLink" runat="server"></asp:Label>
<asp:Button ID="btnCopy" runat="server" Text="Copy link" OnClientClick="copyToClipboard('#ContentPlaceHolder1_lblFileLink')" />
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
Upvotes: 0
Views: 2881
Reputation: 548
instead of using this:
<asp:Button ID="btnCopy" runat="server" Text="Copy link"
OnClientClick="copyToClipboard()" />
because when using asp.net controllers run at server it post back to server.
using button html tag.
<button id="btnCopy" click="copyToClipboard()">Copy link</button>
or you can do this:
<asp:Button ID="btnCopy" runat="server" Text="Copy link"
OnClientClick="copyToClipboard(); return false;" />
Upvotes: 1