There is such code:

<input class="field" type="number"> <input class="field" type="number"> <input class="field" type="number"> <button id="btn">Click</button> <p>XXX<p> (function() { let text = document.querySelector('p'); let fields = document.querySelectorAll('.field'); let btn = document.querySelector('#btn'); btn.addEventListener('click', function() { for(var i = 0; i < fields.length; i++) { text.textContent = fields[i].value; console.log(fields[i].value) } }) })() 

I need to write the values ​​of each input's to the p element when I click on the button. But for some reason my code writes the value of only the last field, while the console displays the values ​​of all fields. Where is the mistake?

1 answer 1

 (function() { let text = document.querySelector('p'); let fields = document.querySelectorAll('.field'); let btn = document.querySelector('#btn'); btn.addEventListener('click', function() { var newText = ""; for (var i = 0; i < fields.length; i++) { newText += fields[i].value; console.log(fields[i].value); } text.textContent = newText; }) })(); 
 <input class="field" type="number" value="12" /> <input class="field" type="number" value="34" /> <input class="field" type="number" value="56" /> <button id="btn">Click</button> <p>XXX</p> 

  • If you also explained)) - RavenTheX pm
  • @RavenTheX You assign text.textContent = fields[i].value; . Naturally, in the end text.textContent will be equal to the left side of the last assignment. - Igor
  • @RavenTheX Right part, of course. - Igor
  • that's just in fact the event is triggered for all inputs. And now when I try to convert a value to a number, I also have all NaN written down - RavenTheX 4:44 pm
  • @RavenTheX What "fact"? Express, please, in Russian. What event for input? The event you have in the code - for the button. - Igor