Reputation: 17927
I'm trying to create and export from my application (CLIENT SIDE), a bunch of CSV files. For the export part, this is the path I've followed so far (FYI, I'm also using jquery mobile for the UI part):
<a>
in the HTML with href='#
download
,target
and href
attributes of that <a>
using jquery, passing respectively the filename, the file content (a string) and the _blank
value.This is the code, to make it more clear:
HTML
<a href="#" id="btn1" data-role="button">download 1</a>
JQUERY
$("#btn1").attr({
'download' : 'file1.csv',
'href' : "file;one",
'target' : '_blank'
});
The resulting button works fine, the file is correctly downloaded as you can see here: FIDDLE (the downloaded file seems to be broken, but I think is a fiddle thing.. locally, it works great)
Now, as I said before, I need to export more than one CSV file at once. My approach is to create as many <a>
as I need, set the download
,target
and href
attributes for each <a>
and then create a download_all-button
that, sequentially, triggers each button's click. This is the code:
HTML
<div id="mypage" data-role="page">
<a href="#" id="btn1" data-role="button">download 1</a>
<a href="#" id="btn2" data-role="button">download 2</a>
<a href="#" id="btn3" data-role="button">download 3</a>
<a href="#" id="downloadall" data-role="button" >DOWNLOAD ALL</a>
</div>
JQUERY
$("#btn1").attr({
'download' : 'file1.csv',
'href' : "file;one",
'target' : '_blank'
});
$("#btn2").attr({
'download' : 'file2.csv',
'href' : "file;two",
'target' : '_blank'
});
$("#btn3").attr({
'download' : 'file3.csv',
'href' : "file;three",
'target' : '_blank'
});
$("#downloadall").on("click", function(){
document.getElementById("btn1").click();
document.getElementById("btn2").click();
document.getElementById("btn3").click();
});
Again, here's the fiddle : FIDDLE DOWNLOAD ALL
This seems to work too, great! Now the questions:
.click()
and it doesn't work calling jQuery .trigger("click")
? (see fiddle here: TRIGGER CLICKdownload
attribute?Thanks in advance for your help, best regards
Upvotes: 0
Views: 2507
Reputation: 24526
is the right approach? I didn't find a lot more on the internet about "export a csv using JS client side"..
why it does work using the .click() and it doesn't work calling jQuery .trigger("click")?
In firefox, that piece of code seems to open new tabs instead of downloading the file.. is related to the download attribute?
target="_blank"
means "open in new tab". Try target="_top"
or target="_self"
.Upvotes: 2
Reputation: 757
Try this:
$("#downloadall").on("click", function(){
document.getElementById("btn1").click()+document.getElementById("btn2").click()+document.getElementById("btn3").click();
/*document.getElementById("btn2").click();
document.getElementById("btn3").click();*/
});
Upvotes: 0