Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all text then copy it in javascript [duplicate]

I have a code which if I selected some text and then clicked copy it works.

My problem if I not select any text and click copy then I must copy all text.

My HTML:

<textarea id="txt" style="width:100%;height:100px;">To enjoy good health</textarea>

<div align="center"><button class="btn-md">copy</button></div>

My Script:

$(document).ready(function(){
   $('.btn-md').click(function(){
     $('#txt').focus();
     document.execCommand('copy');
   });
});
like image 306
Jsparo30 Avatar asked Jun 18 '26 07:06

Jsparo30


1 Answers

Try

$(document).ready(function(){

    $('.btn-md').click(function(){
        var selectedText = getSelectedText($('#txt')[0]);

        if(getSelectedText($('#txt')[0]) != '') {
          
            copyToClipboard(selectedText);
        } else {
            $('#txt').focus().select();
        }
        document.execCommand('copy');
    });
});

function getSelectedText(e) {
    var text   = "",
        start  = e.selectionStart,
        finish = e.selectionEnd;
    text   = e.value.substring(start, finish);
    return text;
}

function copyToClipboard(text){

    var et = $('<textarea/>',{
       css:{ opacity: '0' }
    });
    $('body').append(et);
    $(et)[0].value = text;
    $(et).focus().select();
    document.execCommand('copy');
    $(et).remove();

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<textarea id="txt" style="width:100%;height:100px;">To enjoy good health</textarea>
<div align="center"><button class="btn-md">copy</button></div>
like image 119
Adam Azad Avatar answered Jun 20 '26 22:06

Adam Azad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!