0

iam not understanding how to copy to clickboard as soon as I click on a textarea..I mean it should select all content inside it and then it should pop and and ask something like 'press ctrl c' to copy into clipboard..

I already have a code BUT unable to select full text in text area and should copy into clipboard..

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <script type="text/javascript">

function myfunc2() {
 var selectedobj=document.getElementById('showthis');

  if(selectedobj.className=='hide'){  //check if classname is hide 
    selectedobj.style.display = "block";
    selectedobj.readOnly=true;
    selectedobj.className ='show';
  }else{
    selectedobj.style.display = "none";
    selectedobj.className ='hide';
 }
}


function copyToClipboard (text) {
  window.prompt ("Copy to clipboard: Ctrl+C, Enter", text);
}



function select_all()
{
// alert(document.getElementById("showthis").value);

var text_val=eval("document.getElementById('showthis').value");
text_val.focus();

var copy = text_val.select();
window.prompt ("Copy to clipboard: Ctrl+C, Enter", copy);

}

</script>
 </head>

 <body>


            <label  onclick="myfunc2()">Click here</label>
            <textarea id="showthis" style="display:none" class="hide"  onclick="select_all()" readonly>dfdsfsfasdfdsfsfasdfssdfsfasf</textarea>


 </body>
</html>


could anyone pls look into this...

EDITED: I need only Javascript code (not JQuery)

Otero
  • 29
  • 1
  • 2
  • 8

3 Answers3

2

try this code to select text inside TextBox or TextArea:

<textarea id="txtSelect">Hello</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("txtSelect");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome's little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>

if you need to select text and get it copied to clipboard i think you should a plugin for that purpose. Look at this question :: Copy text to the client's clipboard using jQuery

Community
  • 1
  • 1
ebram khalil
  • 8,252
  • 7
  • 42
  • 60
1

On the base of your code I have developed the following example, hope it will be helpfull:

HTML:

<textarea id="showthis" class="hide" readonly>click to copy</textarea>

JS:

$(function(){
    var select_all = function(control){
        $(control).focus().select();
        var copy = $(control).val();
        window.prompt ("Copy to clipboard: Ctrl+C, Enter", copy);
    }
    $("#showthis").click(function(){
        select_all(this);
    })
})
Warlock
  • 7,321
  • 10
  • 55
  • 75
-1

Using JQuery, It will be just:

$('#showthis').select()

Using just javascript:

document.getElementById('showthis').select()
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57