Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a link and click it on a single button click

I need to create a link on button click and also click that link with same click. I am testing the approaches mentioned on

<script type="text/javascript">
function download()
{
  alert("Hello");
  var link=document.createElement("a");

  link.href="https://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using-   javascript";
document.getElementById(link).click();

// here it says "cannot click on null", means id is not link, then how can i obtain the id

alert("Hello again");

}
</script>
<button type ="button" value="Download" onClick="download();">Downloads</button>

I need this, because, on click of button, i will be making a get call, and i will receive a URL, and then i need to click the URL (Making Download button, link can vary). Is there any other way of doing this?

I refferd: How do I programmatically click a link with javascript?

and

How do I create a link using javascript?

for achieving this, but no success.

like image 286
Vivek Vardhan Avatar asked Oct 22 '25 09:10

Vivek Vardhan


1 Answers

It seems you really just want to change the location of the page, and not actually append a link at all:

location.href = 'your link you got back'

If you actually want a physical link to be added on the page:

var link=document.createElement("a");
link.id = 'someLink'; //give it an ID!
link.href="http://stackoverflow.com/questions/4772774/how-do-i-create-a-link-using-   javascript";

//Add the link somewhere, an appendChild statement will do.
//Then run this
document.getElementById('someLink').click();
like image 74
tymeJV Avatar answered Oct 24 '25 23:10

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!