Reputation: 47
Need the form below to be able to download a pdf file based on the users entry.
If a user enters 1234 and hit enter key or download button, the 1234.pdf file gets downloaded.
If a user enters 12345, the 12345.pdf file gets downloaded.
<form action="">
<span class="text-red">Invalid Code</span>
<div class="input-group input-group-lg">
<input type="text" class="form-control" value="" required/>
<input class="btn btn-primary" type="submit" value="DOWNLOAD" />
</div>
</form>
Upvotes: 0
Views: 327
Reputation: 1268
Change your HTML code as per the following.
<form onsubmit="downloadURI()">
<span class="text-red">Invalid Code</span>
<div class="input-group input-group-lg">
<input type="text" id="fileNumber" class="form-control" value="" onkeypress="OnEnterKyePress(event)" required/>
<input class="btn btn-primary" type="submit" value="DOWNLOAD" />
</div>
</form>
And use the following JavaScript code. Here ../ means the root of the HTML file. ../Data means there is a Data folder at the root of the HTML file.
function OnEnterKyePress(e){
if (e.keyCode == 13)
{
ldownloadURI();
}
}
function downloadURI()
{
var fileNumber=document.getElementById("fileNumber").value;
var fileUri="../data";
downloadFile(fileUri, fileNumber+".pdf");
}
function downloadFile(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = URI;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
Upvotes: 1