0

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>

2
  • for the scenario explained by you. The Id should be unique so easy for identify Commented Jul 10, 2017 at 7:48
  • @RohitPoudel Thanks much! It's working now!!!!!! Commented Jul 10, 2017 at 8:10

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

@daremachine Good point out there, but return false; is 100% browser compatible, and I also think it's a lot clearer than that example.
Agree 100% with you, I wanted give point about pass 'this' as function parameter which is doing what OP need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.