Home > Back-end >  How to change the value of all input boxes at once by looping after inputting the value in the input
How to change the value of all input boxes at once by looping after inputting the value in the input

Time:10-03

I am a beginner in javascript ~ I have a requirement, I hope I can enter some numbers in the input box A at the bottom, after pressing send ~ I can change all the values ​​in the top five input boxes to the input box A. It feels like it can be done using forEach, but I don't know how to start making changes, I hope everyone can help, thank you.

let jsInput = document.querySelector('#js-input');
let jsSend = document.querySelector('#js-send');
jsSend.addEventListener('click', function() {
  console.log(jsInput.value)
})
<input type="text" value="123">
<input type="text" value="666">
<input type="text" value="345">
<input type="text" value="1000">


<h2>I want to change all this numbe</h2>
A <input type="text" id="js-input"><button id="js-send">send</button>

CodePudding user response:

You can do it by adding a class to your other inputs that you want to change and then use getElementsByClassName to get them all and change their value inside a for loop since this return an array

let jsInput = document.querySelector('#js-input');
let jsSend = document.querySelector('#js-send');
jsSend.addEventListener('click', function() {
    const inputs = document.getElementsByClassName('inputc');
  for (let i = 0; i < inputs.length; i  ) {
    inputs[i].value=jsInput.value;
  }
  
})
<input  type="text" value="123">
<input  type="text" value="666">
<input  type="text" value="345">
<input  type="text" value="1000">


<h2>I want to change all this numbe</h2>
A <input type="text" id="js-input"><button id="js-send">send</button>

  • Related