Reputation: 137
Is there a way to do a selection highlight over all elements in a HTML Table?
I want to be able to have data displayed in a tabular form, and the user to be able to click a button to select the relevant data to copy and paste into the spreadsheet of their choosing.
Upvotes: 0
Views: 1083
Reputation: 14758
Try this:
function selectAll(parentNode) {
var sel;
// IE
if (document.selection) {
sel = document.body.createTextRange();
sel.moveToElementText(parentNode);
sel.select();
} else {
sel = document.createRange();
sel.setStartBefore(parentNode);
sel.setEndAfter(parentNode);
window.getSelection().addRange(sel);
}
}
selectAll(document.getElementById('myTable'));
Test it out here.
Upvotes: 3
Reputation: 56123
When I wrote an abstraction for the API to select data, I wrote the following comments. You might find the various URLs (which I cited in my comments) useful.
This interface isn't based on a W3C standard. Instead it's based on de facto interfaces from various browsers. It represents the object that's returned when you invoke the javascript window.getSelection() method as described at http://www.quirksmode.org/dom/range_intro.html
The MS IE version of this interface is the type of the "selection" object in the Microsoft API which can be found via http://www.google.ca/search?hl=en&q=html+and+dhtml+reference
However this interface is based more on the Mozilla API (instead of the MS IE API). The Mozilla interface can be found at http://mxr.mozilla.org/mozilla/source/content/base/public/nsISelection.idl and https://developer.mozilla.org/en/DOM/Selection
If you're using a Javascript library like jquery, that might hide/abstract the browser-specific differences for you and give you a unified API.
Upvotes: 0
Reputation: 171511
Since most browsers already provide this functionality by letting the user select the text manually, why not provide the user with a link to download the data in Excel-compatible format, such as CSV? This is a more robust solution if you ever get enough data that you have to page, for example.
Upvotes: 0