JavaScript Input text per value attribute in onClick

yagami cell :

I wanted to input the number which I click to the text box from the attribute value present on that number.

If I click number 1 then the value is number 1 and so on.

This is my script:

function myFunc() {
  var dadada = document.getElementsByTagName("a");
  var i;
  for (i = 0; i < dadada.length; i++) {
    var de = dadada[i].getAttribute("value");
  }
  document.getElementById("text_id").value = de;

}
<div id="xxx">
  <a class="list-group-item" href="#" value="1" onclick="myFunc()">1</a>
  <a class="list-group-item" href="#" value="2" onclick="myFunc()">2</a>
  <a class="list-group-item" href="#" value="3" onclick="myFunc()">3</a>
  <a class="list-group-item" href="#" value="4" onclick="myFunc()">4</a> 
this value: <input type="text" id="text_id" value="">

Maheer Ali :

You need to get the value of the clicked link. Get all the <a> in javascript using querySelectorAll() and then loop through them and addEventListener to them.

Use the eventObject e and get the attribute value of the clicked link

const items = document.querySelectorAll('.list-group-item');
items.forEach(item => {
  item.addEventListener('click', e => myFunc(e))
})

function myFunc(e) {
    document.getElementById("text_id").value =e.target.getAttribute('value')
}
<div id="xxx">
<a  class="list-group-item" href="#" value="1">1</a> 
<a  class="list-group-item" href="#"  value="2">2</a> 
<a  class="list-group-item" href="#"  value="3">3</a> 
<a  class="list-group-item" href="#"  value="4">4</a>    
this value: <input type="text" id="text_id" value="">

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31730&siteId=1