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)
    }
}
2
  • 1
    text.forEach((word, i) => { ... }); (you have nested loops, but you want to iterate over both iterables at the same time) Commented Mar 30, 2020 at 12:24
  • You might want to change this document.getElementById(inputs[i]).textContent(word) to document.getElementById(inputs[i]).textContent = word; Commented Mar 30, 2020 at 12:26

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.