How to Trigger a File Download by Clicking a Button in jQuery? | Code snippet #30
Code Snippet #29: The code shows us how to click a input button to invoke a file download in <a> tag using jQuery.
Since triggering click event on a hyperlink with jQuery may not behave the way you expect it to behave like it behaves with an input button or any other element. This is true especially when you want to trigger the click on a hyperlink (<a href=”>) tag to download file. In this code snippet we will see how to trigger a download from “a” tag using a click on an input button.
Here we will the following things:
- Create an input button
- Create a hyperlink for downloading the file
- Trigger the download by clicking the input button created in the first step.
<input type="button" class="downloadButton" value="download" />
<a href="url" class="downloadLink">Hyperlink</a>
var href = $('.downloadLink').attr('href');
window.location.href = href;