Abhishek
Abhishek

Reputation: 717

Download multiple files on a page using jQuery

I have a page which has a many links of files to be downloaded individually. I thought it would be a good to have feature to trigger download for all the files with a single click. Here's the script which I wrote to test this-

$('tbody tr a').slice(1).each(function(){  //don't mind the slice().
    console.log('starting download of: ' + $(this).attr('href')); // for debugging.
    $(this).attr('target','_blank'); //  so that a new page is opened for download.
    window.location.href = $(this).attr('href');
})

The problem is that the script only triggers the download of only first download link. However, if I see console, the log is printed for all the files. I think it's happening because of page redirection. Can anyone help me get around this?

Upvotes: 0

Views: 3248

Answers (2)

guest271314
guest271314

Reputation: 1

Try substituting download attribute for window.location.href = $(this).attr('href'), call .click() on each <a> element within filtered selector $("tbody tr a").slice(1) at .each() at click of <button> element

var a = $("tbody tr a").slice(1);

$("button").click(function(e) {
  // download `a.txt`, `b.txt`
  a.each(function() {
    this.click()
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>
        <a href="data:text/plain,1" download="1.txt">1</a>
      </td>
    </tr>
    <tr>
      <td>
        <a href="data:text/plain,a" download="a.txt">a</a>
      </td>
    </tr>
    <tr>
      <td>
        <a href="data:text/plain,b" download="b.txt">b</a>
      </td>
    </tr>
  </tbody>
  <!-- click to download `a.txt`, `b.txt` -->
  <button>download all files</button>

Upvotes: 2

Kosta B.
Kosta B.

Reputation: 271

You may want to see this answer here:

jquery trigger ctrl + click

Just run on all of your links and trigger ctrl+click in order to open links in new page.

Upvotes: 0

Related Questions