Skip to content

Instantly share code, notes, and snippets.

@nicodevs
Created July 5, 2018 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicodevs/fe5174c28748b5f542c01b8185cde2a3 to your computer and use it in GitHub Desktop.
Save nicodevs/fe5174c28748b5f542c01b8185cde2a3 to your computer and use it in GitHub Desktop.
Download Table jQuery Plugin
/*
Download Table - jQuery plugin
written by Nico Beta
http://github.com/nicobeta
Markup:
<a href="#table" id="test" data-filename="clients">Download</a>
- href: table selector
- data-filename: name of the downloadable file
How to use:
$('#test').downloadTable();
*/
(function($) {
$.fn.extend({
downloadTable: function() {
var cellDel = ",",
rowDel = "\r\n",
table = [],
blob,
target = $(this).attr('href'),
filename = $(this).data('filename') || 'table';
$(target).find('tr').each(function() {
row = [];
$(this).children().each(function() {
row.push($(this).text());
});
table.push(row.join(cellDel));
});
table = table.join(rowDel);
blob = new Blob([table], {"type": "text/csv"});
$(this).attr({
href: window.URL.createObjectURL(blob),
download: filename + '.csv'
});
return this;
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment