How do I use variables in my href when downloading a file?

211 views Asked by At

JavaScript

I have three variables that I would like to use to define the href for downloading a file:

var fSelect;
var uSelect;
var bSelect;

So my href would be defined by a variable like this:

var saveFile = '../files/' + fSelect + uSelect + bSelect + '.x3g';

HTML

But then how do i use this in my HTML document?

<a><img src="../save-button.png" alt="Save" width="120" height="40" /></a>
2

There are 2 answers

0
James McDowell On

Give the img tag an ID attribute (in this case, I'm using img)
Then modify the tag using DOM

document.getElementById("img").src = saveFile;

0
Yeldar Kurmangaliyev On

As I have understood, the question is "how to start downloading file when I have a safeFile variable"?

<a id="saveFileHref" href="#">
   <img src="../save-button.png" alt="Save" width="120" height="40" />
</a>

In JavaScript:

document.getElementById('saveFileHref').onclick = function() {    
    var saveFile = '../files/' + fSelect + uSelect + bSelect + '.x3g';
    window.location.href = saveFile;
};

JavaScript onclick event lets you define a behaviour of clicked element. window.location.href lets your change the current URL.

It is a good approach if your fSelect, uSelect and bSelect are chosen on the page and url should be generated dynamically. If you have a calculated safeFile value at the beginning of loading, you can set it in the beginning:

document.getElementById('saveFileHref').src = '../files/' + fSelect + uSelect + bSelect + '.x3g';