Click on the download link using jQuery does not download the file

I have a link with href and download attributes:

<a id="lnk" href="data:text/csv;charset=utf-8,1%2C2%2C3" download="my_file.csv">click to download</a> 

When I click on it (for example, in Chrome), the csv file "my_file.csv" loads as intended.

Now I want this action to be called programmatically. Therefore, using jQuery, I try:

 $('#lnk').click(); 

or

 $('#lnk').trigger("click"); 

but the file is not uploaded.

Here is the code: http://jsbin.com/yereg/3/edit

I could copy the link address from the link, and then just use window.open:

 window.open('data:text/csv;charset=utf-8,1%2C2%2C3'); 

but this way I can’t set the file name (the link has the attribute download="my_file.csv" ). This solution is great if there is a way to set the file name.

Note: in my case, Chrome and Firefox must be supported. I don’t care what other browsers are.

+5
source share
2 answers

from jquery documentation:

The click event fires only after this exact series of events:

The mouse button is pressed when the cursor is inside an element. The mouse button is issued when the pointer is inside the element.

You can resort to invoking a native JavaScript event through

 $('#lnk').get(0).click(); 

Or safer:

 var lnk = document.getElementById('lnk'); if (lnk) { lnk.click(); } 

EDIT:

Out of curiosity, I looked at jQuery sources on how to do this. It turns out that they prevent the natural event of a browser click on the links specifically, see the following excerpt from events.js in the latest version of jQuery (2.1.x), especially the comment:

 click: { [...] // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, 
+15
source

Try using $('#lnk')[0].click()

JS:

 $('#btn1').on('click', function(){ $('#lnk')[0].click(); }); 
+1
source

Source: https://habr.com/ru/post/1201160/


All Articles