KevMoe
KevMoe

Reputation: 443

Download csv on document.ready rather than on click

I am hitting a wall in trying to get this tabletocsv code converted so that it will automatically download when the page loads. I have attempted a variety of things including having a separate function that automatically clicks the button when the page is ready. Nothing is working, any ideas?

$(document).ready(function () {

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row),
                $cols = $row.find('td');

            return $cols.map(function (j, col) {
                var $col = $(col),
                    text = $col.text();

                return text.replace(/"/g, '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"';

            // Deliberate 'false', see comment below
    if (false && window.navigator.msSaveBlob) {

                    var blob = new Blob([decodeURIComponent(csv)], {
              type: 'text/csv;charset=utf8'
        });


        window.navigator.msSaveBlob(blob, filename);

    } else if (window.Blob && window.URL) {
                    // HTML5 Blob        
        var blob = new Blob([csv], { type: 'text/csv;charset=utf8' });
        var csvUrl = URL.createObjectURL(blob);

        $(this)
                .attr({
                    'download': filename,
                    'href': csvUrl
                });
            } else {
        // Data URI
        var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

                    $(this)
            .attr({
                  'download': filename,
                'href': csvData,
                'target': '_blank'
                });
    }
}

// This must be a hyperlink
$(".export").on('click', function (event) {
    // CSV
    var d = new Date();
    var args = [$('#output>table'), d+'heartbeat.csv'];

    exportTableToCSV.apply(this, args);

    // If CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
});
})

I thought that changing the click function to this would work, but it doesn't:

 $(".export").ready(function (event) {
    var d = new Date();
    var args = [$('#output>table'), d+'heartbeat.csv'];

    exportTableToCSV.apply(this, args);

});

Html:

<a href="#" id="daily" class="export"><button class="download">Download Report</button></a>

I also tried to use the id "daily" on the button instead of the link.

Here is a link to jfiddle for testing:

https://jsfiddle.net/db6uqLtz/

Upvotes: 0

Views: 362

Answers (1)

oompahlumpa
oompahlumpa

Reputation: 503

I added $(".download").trigger("click"); and it worked like a charm.

$(document).ready(function () {

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row),
                $cols = $row.find('td');

            return $cols.map(function (j, col) {
                var $col = $(col),
                    text = $col.text();

                return text.replace(/"/g, '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"';

            // Deliberate 'false', see comment below
    if (false && window.navigator.msSaveBlob) {

                    var blob = new Blob([decodeURIComponent(csv)], {
              type: 'text/csv;charset=utf8'
        });


        window.navigator.msSaveBlob(blob, filename);

    } else if (window.Blob && window.URL) {
                    // HTML5 Blob        
        var blob = new Blob([csv], { type: 'text/csv;charset=utf8' });
        var csvUrl = URL.createObjectURL(blob);

        $(this)
                .attr({
                    'download': filename,
                    'href': csvUrl
                });
            } else {
        // Data URI
        var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

                    $(this)
            .attr({
                  'download': filename,
                'href': csvData,
                'target': '_blank'
                });
    }
}

// This must be a hyperlink
$(".export").on('click', function (event) {
    // CSV
    var d = new Date();
    var args = [$('#output>table'), d+'heartbeat.csv'];

    exportTableToCSV.apply(this, args);

    // If CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
});

//Added this, and it does wheat you want.
$(".download").trigger("click");

})

 $(".export").ready(function (event) {
    var d = new Date();
    var args = [$('#output>table'), d+'heartbeat.csv'];

    exportTableToCSV.apply(this, args);

});

Upvotes: 1

Related Questions