Aboud Jouda
Aboud Jouda

Reputation: 107

How to pass value from href to input

Need some guidance. I am trying to pass a value from href to an input value using getAttribute and it works fine, but if I used more than one a tag it only shows href attribute for the first one.

Pls, check the code snippet,

function myFunction(event) { 
    document.getElementById("demo").value = document.getElementsByTagName("a")[0].getAttribute('href');
}
<a href="#2" onclick="myFunction(event)">test1</a>

<a href="#3" onclick="myFunction(event)">test2</a>

<input id="demo"></input>

Upvotes: 0

Views: 49

Answers (2)

Ele
Ele

Reputation: 33726

Your problem is the following:

// That line is returning always the first <a> element, so you're getting always '#2'.
document.getElementsByTagName("a")[0]; 

You can learn a little more here Element.getElementsByTagName()


You can pass the element directly to your function myFunction.

Look this code snippet:

function myFunction(caller) {
  document.getElementById("demo").value = caller.getAttribute('href');
}
<a href="#2" onclick="myFunction(this); event.target">test1</a>

<a href="#3" onclick="myFunction(this); event.target">test2</a>

<input id="demo"></input>

See, now the input is getting the right href value.

Upvotes: 3

antelove
antelove

Reputation: 3348

Dynamically, you can do the same thing like this,

var a = document.querySelectorAll("a");

for (var i in a) {
  a[i].onclick = function() {
     document.getElementById("demo").value = this.getAttribute("href");
  };
}
<a href="#1" >test1</a>
<a href="#2" >test2</a>

<input id="demo" />

Upvotes: 0

Related Questions