OmbraDiFenice/table2csv

How do I get the example to work?

Closed this issue · 1 comments

I'm not good at Javascript, so I might have done something strange, but I don't get your example to work. When I run the attached index.html i only see the table – no button, no downloaded file. I don't know what I should expect – a button? (Or do I need to specify in my Javascript that there should be a button? If so, how do I specify that I want a download button below the table?)
table2csv_test.zip

Hello, thank you for trying this small plugin :) sorry for missing this for so long...
you're almost there, but I see a couple of problems in your test code.

First of all in my example I'm using $("table").first() as a JQuery selector. This first selects all the <table> elements in the page, and then takes the first (and only in your case) one with first(). In this way the following call to table2csv() happens on the table you want to download.
In your code you have instead $("tab").first(). I assume that you wanted to select the table using its id rather than using the html element name, but you forgot to put the # in front of the id :) Also, if you use the id to select something, calling first() after that is (or should be) useless, since the id should be unique in the page (even though sometimes it isn't, but that's actually an error in the html... the thing is that browsers work anyway, so these kind of problems are not always catched).

The second problem is that you put the <script> tag before the table in the <body>. That means that your javascript code gets executed before the table is actually created. What happens is that JQuery looks for the selected element, but since it doesn't exists yet it returns an empty result and of course the call to table2csv() cannot work. If you open the javascript console in the browser you will see that this results in the error table2csv must be called on a <table> element.

So all in all what you need to do is

  1. change your javascript code into $("#tab").table2csv() (you can retain the .first() in the middle if you want, it doesn't change anything)
  2. move your <script> at the bottom of the <body> element. Doing so will start the download of the csv as soon as you load the html page. If you prefer, you can hook up the same code to the onclick of a <button> element, so that you will be able to trigger the download manually.

I hope this help you :)