0

I have some input elements like

<input type="text" name="d1">
<input type="text" name="d2">

and so on

<input type="text" name="d10">

Now I would like to select all of them for some javascript query document.form_name.d1 through document.form_name.d10, using a for loop, so that I dont have to write each one of them separately. How to do this?

3
  • please show html Commented Oct 14, 2019 at 7:05
  • Add them a class and select by class. Commented Oct 14, 2019 at 7:20
  • Thanks u_mulder and Nikita. Will try both and get back to you guys. Commented Oct 15, 2019 at 9:54

2 Answers 2

1

Add some class to your inputs and use getElementsByClassName:

var inputs = document.getElementsByClassName('text-input');
for (var i = 0; i < inputs.length; i++) {
    console.log(inputs[i].value);
}
<input type="text" name="d1" class="text-input" value="value 1">
<input type="text" name="d2" class="text-input" value="value 2">
<input type="text" name="d3" class="text-input" value="value 3">
<input type="text" name="d4" class="text-input" value="value 4">
<input type="text" name="d5" class="text-input" value="value 5">

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

1 Comment

I think this solution is better than Nikita's because it is more scalable. This avoids "name" having 2 responsibilities (naming the field, and knowing if this field should be taken from its list). Imagine that the names of the fields change, or that its selection should not contain d2, but d1 and d3, etc ...)
1

Also, you can use javasctipt querySelectorAll to get all elements starts with "d"

document.querySelectorAll("[name^=d]");

1 Comment

Thanks u_mulder and Nikita. Will try both and get back to you guys.

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.