Archive

Archive for the ‘javascript’ Category

Export HTML table as CSV file using JQuery

April 9, 2012 Leave a comment

Put this code into a script section into a common HTML head include file:

$(document).ready(function() {

  $('table').each(function() {
    var $table = $(this);

    var $button = $("<button type='button'>");
    $button.text("Export to spreadsheet");
    $button.insertAfter($table);

    $button.click(function() {
      var csv = $table.table2CSV({delivery:'value'});
      window.location.href = 'data:text/csv;charset=UTF-8,'
                            + encodeURIComponent(csv);
    });
  });
})

Note:

  • Requires JQuery and table2CSV (i.e. put script references before the script above)
  • “table” selector is a JQuery selector and can be adjusted to suit your needs
  • Only works in browsers with full “Data URI” support (Firefox, Chrome, Opera) but not in IE (which only supports this for images)
  • For full browser compatibility you would have to use a slightly different approach that requires a server side script (e.g. a Java Servlet) to “echo” the CSV. Maybe I will blog about that in another post.
Categories: javascript

JQuery DataTables column filters state saving

December 12, 2011 Leave a comment

The JQuery DataTables plugin supports state saving for column filters. But it does not automatically set the column filter values to the saved values when the user navigates to a page that has saved filter state.

I saw the code suggested here and cleaned it up a little (for example, using the oSettings parameter of the fnInitComplete function).

$(document).ready(function() {

        var oTable = $('#REPLACE_THIS_WITH_TABLE_ID').dataTable({
            "bStateSave": true,
            "fnInitComplete": function(oSettings, json) {
                var cols = oSettings.aoPreSearchCols;
                for (var i = 0; i < cols.length; i++) {
                    var value = cols[i].sSearch;
                    if (value.length > 0) {
                        $("tfoot input")[i].value = value;
                    }
                }
            }
        });

        $("tfoot input").keyup(function () {
            oTable.fnFilter(this.value, $("tfoot input").index(this));
        });
    });

Please note that I completely removed all code that supported initial display texts in the filter fields (because I don’t use that).

Categories: javascript
Follow

Get every new post delivered to your Inbox.