Tuesday, 10 May 2016

Code to copy paste using javascript on clipboard

Working on Chrome, IE, Mozilla

 Script:

function copySelectionText(text) {
    //debugger;
    var copysuccess;
    try {
        if (window.clipboardData && clipboardData.setData) {
            clipboardData.setData('text', text);//For IE
        }
        else {//For others
            copysuccess = document.execCommand("copy");
        }
    } catch (e) {
        copysuccess = false;
    }
    return copysuccess;
}

function copyfieldvalue(e, field) {
    SelectText(field);
    var copysuccess = copySelectionText(field.innerText);
}

function SelectText(element) {
    var doc = document
        , text = element
        , range, selection
    ;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

Html Changes:

 <button data-bb-handler="ok" type="button" id="btnOtpCopy" data-dismiss="modal" onclick="copyfieldvalue(event,document.getElementById('otpValue'));" class="btn btn-primary">Copy</button>

No comments:

Post a Comment