0

So,pretty much I've run into a problem with my script. I'm trying to make a download script (memory only,so no downloading using HTML/PHP that would cost servers to load more than I want). What I've done is gotten a script off of here (credit Matěj Pokorný). The point is to download a txt file with a random number,it is assigned a var "x", this x is defined in the same script. x is defined as a random number (1-10 * 1000 FLOORED) so example it would be 1234.txt when it downloaded. Unfortunately I have no idea how to define variables in onclick,would someone willing to fix this up for me? I tried moving the variable around and putting the 's around the txt and the whole thing and everything but to no avail. I'm SOO sorry how stupid this is but maybe my crazy stupid question could help someone else.

Script on JSFiddle: https://jsfiddle.net/Xevion/btpmweb9/1/

HTML

    <h1>Z</h1>
<p>Z</p>
<button onclick="download(x'.txt', 'Hello world!');" type="button" class="btn btn-lg btn-success btn-block">Download</button>

Javascript

var x = Math.floor((Math.random() * 1000) + 1);function download(filename, text) {
var pom = document.createElement('a');

pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);

if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    pom.dispatchEvent(event);
}
else {
    pom.click();
}
Community
  • 1
  • 1
Xevion
  • 13
  • 3
  • Do everything inside your function. Don't try to pass `x'.txt'` into it. – Teepeemm Nov 02 '15 at 02:27
  • @Teepeemm I'm kinda hoping that I could do externally but,is there no other option? No way to mention variables and combine a part of text within a variable? (foo= x+(.txt) x=?) – Xevion Nov 02 '15 at 02:43

1 Answers1

0

x'.txt' is not a valid type and cannot be parsed by the JS engine. You want to perform string concatenation instead. Replace with x+'.txt' inside your function call.

To grasp the mistake, try this in the console:

var x = "something";

'.txt'; // 'txt'
x; // 'something'
x'.txt'; // SyntaxError: Unexpected string
x+'.txt'; // 'something.txt'

The script should also be included before the button markup, or at least x must have been defined before the onclick function is parsed. A small step to rectify the situation could be to add this anywhere above button:

<script>var x;</script>

By the time you click the button, the original script will have run and x will have taken its value.

Guybrush Threepwood
  • 1,253
  • 1
  • 11
  • 21