In This article we will discuss about How to Copy Clipboard data using JavaScript.
There are Certain Scenarios came into development or sometimes Client requirement to Copy ClipBoard data of a Particular textbox.
There are Certain 3rd Party tools present but the same functionality is present in Javascript.However, 3rd Party tools having Certain Pros and Cons, So it is better to Use Javascript to implement Copy ClipBoard Functionality.
Let me take an example to implement the ClipBoard Example.
Example:-
-----------
Take a Simple aspx page add one TextBox,one Button and a span whcih is as below,
<input type="text" id="txtBoxCopy"/>
<button id="btnCopy">Click to Copy</button>
<span id="spanAnswer">
Here i used Html tag but still we can use asp Controls.
Now, in the Script tag we need to write some code and after that we can able to Copy Clipboard data which is as below,
<script>
$(document).ready(function(){
var ClipBoardData=document.getElementById("txtBoxCopy");
var btnClickCopy=document.getElementById("btnCopy");
var CopiedData=document.getElementById("spanAnswer");
btnClickCopy.addEventListener('click',function(e){
ClipBoardData.select();
try{
var ok=document.execCommand("btnClickCopy");
if(ok) CopiedData.innerHTML="Copied!";
else CopiedData.innerHTML="Unable to Copy!";
} catch(err){
CopiedData.innerHTML="UnSupported Browser!";
}
)};
)};
</script>
In the above Code, i added an Click event listener for Button.
So whenever we add some text in textbox and click on button then click event will hit and at first the textbox will Select all text and whenever execCommand will execute at that time the data will be Coiped and we are displaying the Copied data in our Span tag.
Note:- Please include the Jquery file otherwise it will show you Jquery is not defined.
0 comments:
Post a Comment