Naman Bhardwaj
Naman Bhardwaj

Reputation: 63

I want to get url from the same document using JS onclick method

I'm trying to get url from some links. If I click on the google link, output should be google.com and for other links should be the same. But I don't know how to do that. Sorry I'm too new to programming. Help me out please.Thank you My code is here, please guide me well for this task. Thanks again...`

<script>
function get_url() {
    document.getElementById("field1").value = document.getElementById("url").value;
}
</script>
<a onclick="get_url()" target = "_blank" id = "url"  href="http://www.google.com/">Google </a> <br/>
<a onclick="get_url()" target = "_blank" id = "url" href="http://www.facebook.com/">Facebook </a><br/>
<a onclick="get_url()" target = "_blank" id = "url" href="http://www.twitter.com/">Twitter </a><br/>
<a onclick="get_url()" target = "_blank" id = "url" href="http://www.youtube.com/">Youtube </a><br/><br/>

URL : <input type="text" id="field1"><br><br>

<p>Click on the link above to get the URL of the linked document.</p>

Upvotes: 0

Views: 50

Answers (1)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

You were almost there - there were just a few issues.

Firstly, you can't have multiple elements with the same ID. IDs should be unique, but you don't actually need them in this instance. Instead I changed it to pass the link into get_url() as a parameter, and then used that to get the href value and insert it into the text box.

Finally, I added return false; to the function, in order to stop the links actually triggering a page change.

function get_url(link) {
    document.getElementById("field1").value = link.href;
    return false;
}
<a onclick="get_url(this)" target="_blank" href="http://www.google.com/">Google </a> <br/>
<a onclick="get_url(this)" target="_blank" href="http://www.facebook.com/">Facebook </a><br/>
<a onclick="get_url(this)" target="_blank" href="http://www.twitter.com/">Twitter </a><br/>
<a onclick="get_url(this)" target="_blank" href="http://www.youtube.com/">Youtube </a><br/><br/>

URL : <input type="text" id="field1"><br><br>

<p>Click on the link above to get the URL of the linked document.</p>

Upvotes: 2

Related Questions