Joker Joker - 3 months ago 12
Javascript Question

How to select and copy multiple <td> value on double click?

i want to select multiple and then copy (ctrl+c).in my code is

<table id="tbl1" border="1">
<tr>
<td>first</td>
<td>second</td>
</tr>
<tr>
<td>third</td>
<td>4th</td>
</tr>
<tr>
<td>5th</td>
<td>6th</td>
</tr>
</table>


my table will show like

______________
|first|second|
_____________
|third|4th |
_____________
|5th |6th |
______________


Here if i double click over "second" , "third" and "5th" then this 3 cells should be selected and then i will use ctrl+c to copy and paste this data in wordpad,i tried dblclick but it works only in firefox.

Answer

I did this snippet (untested), you can use as start:

$(function($) {
    var ctrlDown = false;
    var ctrlKey = 17;
    var cmdKey = 91;
    var cKey = 67;

    $(document).keydown(function(e) {
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) {
            ctrlDown = true;
        }
    }).keyup(function(e) {
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) {
            ctrlDown = false;
        }
    });

    var selection = '';
    $('#tbl1 td').dblclick(function() {
        selection += this.innerHTML;
    }).keydown(function(e) {
        // if (CTRL + C)
        if (ctrlDown && (e.keyCode == cKey)) {
            var $div = $('<div></div>').appendTo('body').html(selection);
            var copyText = $div[0].createTextRange();
            copyText.execCommand('RemoveFormat');
            copyText.execCommand('Copy');
            $div.remove();
            selection = '';
            return false;
        }
    });
});

References: