0

Can anyone help with how do you get the different innerhtml from the same class into an input text? This is the code. Thanks.

function myFunction() {
  var a = document.getElementsByClassName("name");
  var b = document.getElementById("whispering");
  a.innerHTML = b.value;
}
<span onclick="myFunction();" class="name" id="username1"> Username 1 </span>
<span onclick="myFunction();" class="name" id="username2"> Username 2 </span>

<input type="text" id="whispering">
Neof
  • 13
  • 3

3 Answers3

1

Something like this will do the trick:

a[2].innerHTML = b.value;

Or if you want the specific item clicked, you could do:

HTML:

<span id="1" class="name">Content</span>
<span id="2" class="name">Content</span>

JS:

var spans = document.getElementsByClassName("name");

for(var i = 0; i < spans.length; i++){
    spans[i].onclick = function(){
        this.innerHTML = b.value;
    }
}

NOTE: this also stops the use of inline JS :)

Fiddle: https://jsfiddle.net/yn9wauyk/

GROVER.
  • 4,071
  • 2
  • 19
  • 66
1

The issue with your code is that getElementsByClassName returns a collection, so you need to loop through that and set the innerHTML of each individual element:

function myFunction() {
  var a = document.getElementsByClassName("name");
  var b = document.getElementById("whispering");

  for (var i = 0; i < a.length; i++) {
    a[i].innerHTML = b.value;
  }
}
<span onclick="myFunction();" class="name" id="1"> HAHA1 </span>
<span onclick="myFunction();" class="name" id="2"> Haha2 </span>

<input type="text" id="whispering">
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

You would be better to pass a reference to the clicked element into your method - this solves all problems of referencing the correct element by id or by class.

function myFunction(elem) {
   var b = document.getElementById("whispering");
  elem.innerHTML = b.value;
}
<span onclick="myFunction(this);"> HAHA1 </span>
<span onclick="myFunction(this);"> Haha2 </span>

<input type="text" id="whispering">
Jamiec
  • 133,658
  • 13
  • 134
  • 193