Hello i was wondering how can i invoke an a
click from a button
onclick
event:
I have made it work so far with these 2 methods :
<a class="button" type="application/octet-stream" href="http://localhost:5300/File" download>Click here for dld</a>
<input type="button" onclick="location.href='http://localhost:5300/File';" value="Download"/>
But i can not make it work with js
; i have tried like this:
<button onclick="Save('http://localhost:5300/File')">Download</button>
function Save(url){
var link=document.createElement('a');
link.url=url;
link.name="Download";
link.type="application/octet-stream";
document.body.append(link);
link.click();
document.body.removeChild(link);
delete link;
}
PS I need to use the <button></button>
and not the input
!
Add button type='button'
function Save(url) { console.log(url) var link = document.createElement('a'); link.url = url; link.name = "Download"; link.type = "application/octet-stream"; document.body.append(link); link.click(); document.body.removeChild(link); delete link; }
<a class="button" type="application/octet-stream" href="http://localhost:5300/File" download>Click here for dld</a> <button type='button' onclick="Save('http://localhost:5300/File')">Download</button>
Do you actually need to create an a
element? If not, I would use window.location.href
, which is similar to clicking on a link.
Example:
function Save(url){
window.location.href = url;
}
The only issue with this might be if you're linking to an HTTP (non-secure) site from an HTTPS (secure) site.
Your code creates a link, clicks it then deletes it. You can instead just run window.location.href
as you did in the HTML example.
onclick = "Save('http://localhost:5300/File')" > Download < /button> function Save(url) { window.location.href = url; }
<button onclick="Save('http://localhost:5300/File')">Download</button>
Or, if you stick to your method of creating a link, you should set href
for the link, not url
.
function Save(url) { var link = document.createElement('a'); link.href = url; link.name = "Download"; link.type = "application/octet-stream"; document.body.append(link); link.click(); document.body.removeChild(link); }
<button onclick="Save('http://localhost:5300/File')">Download</button>
const btn = document.querySelector('button'); btn.addEventListener('click', function(e) { e.preventDefault(); save('http://localhost:5300/File'); }); function save(url) { let link = document.createElement('a'); link.href = url; link.name = "Download"; link.type = "application/octet-stream"; document.body.append(link); link.click(); document.body.removeChild(link); delete link; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Download</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.