0

I wish to be able to identify all input fields so that i can store them and run a for loop which will input text into the input fields from an array and submit the form for a response.

var inputs = document.forms["form_name"].getElementsByTagName("input");
var text = ["brown", "white", "blue", "green"]


for (var i = 0; i < inputs.length; i++) {
    for (word of text){
        document.getElementById(inputs[i]).textContent(word)
    }
}
I Smokh I
  • 93
  • 1
  • 8
  • 1
    `text.forEach((word, i) => { ... });` (you have nested loops, but you want to iterate over both iterables at the same time) –  Mar 30 '20 at 12:24
  • You might want to change this `document.getElementById(inputs[i]).textContent(word)` to `document.getElementById(inputs[i]).textContent = word`; – Sagar More Mar 30 '20 at 12:26

2 Answers2

1

No need to loop text and no need document.getElementById because already get element for change values use value not textContent

var inputs = document.forms["myForm"].getElementsByTagName("input");
var text = ["brown", "white", "blue", "green"]

for (var i = 0; i < inputs.length; i++) {
     inputs[i].value  = text[i];
}
<form name="myForm" >
f Name: <input type="text" name="fname">
m Name: <input type="text" name="mname">
l Name: <input type="text" name="lname">
dob: <input type="text" name="dob">

</form>
<button>Go to Next</button>
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
1

Don't use getElementsByTagName() or document.forms. Those are old APIs that have drawbacks.

Instead, use .querySelectorAll() and take advantage of the fact that you can loop over the results of .querySelectorAll() with the Array.forEach() method like this:

var values = ["brown", "white", "blue", "green"];

// Loop over all the inputs
document.querySelectorAll("input").forEach(function(input, index){
   // Set the current input with the corresponding item from the values array
   input.value = values[index];
});


// Submit the form
document.querySelector("form").submit();
<form action="https://www.example.com" method="post">
  <div>Input 1 <input name="item1"></div>
  <div>Input 2 <input name="item2"></div>
  <div>Input 3 <input name="item3"></div>
  <div>Input 4 <input name="item4"></div>
</form>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71