views:

396

answers:

1

Hello everyone,

I was wondering if anybody knows how to select using js the complete table, so that the user can right-click on the selection, copy it to the clipboard and then paste it on excel. If you select the table manually, the process works perfectly. But sometimes, if the table height is a few times larger than the screen, selecting it dragging the mouse gets tedious. So, I want to give the users the posibility to click on a "select the whole table" button and everything gets ready to be copied.

Any ideas?

TIA.

Dan.

+4  A: 

Yes. It's not too tricky, and the following will work in all mainstream browsers (including IE 6, and indeed 5):

<script type="text/javascript">
    function selectElementContents(el) {
        var body = document.body, range, sel;
        if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (document.createRange && window.getSelection) {
            range = document.createRange();
            range.selectNodeContents(el);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
</script>

<table id="table">
    <thead>
        <tr><th>Heading</th><th>Heading</th></tr>
    </thead>
    <tbody>
        <tr><td>cell</td><td>cell</td></tr>
    </tbody>
</table>

<input type="button" value="select table"
   onclick="selectElementContents( document.getElementById('table') );">
Tim Down
It worked! Perfect! thanx!
DanC