MKaya9277
MKaya9277

Reputation: 9

Using GetElementByID multiple times, with a for loop?

im having the issue that i want to use the same GetElementByID multiple times, since i cant set it to a defined value - it needs to be scalable.

Part 1:

    <span class="hiddenAV">AV:</span><input type="text" id="AttVector" onfocusout="getBV()">
    <span class="hiddenAC">/AC:</span><input type="text" id="AttComp" onfocusout="getBV()">
    <span class="hiddenPR">/PR:</span><input type="text" id="PRReq" onfocusout="getBV()">

Part 2:

    AV = document.getElementById("AttVector").value;
    AC = document.getElementById("AttComp").value;
    PR = document.getElementById("PRReq").value;

What im trying to do is something like:

    for (i=1; i<40; i++) {
      var i = document.getElementById("AttVector" + i)
    }

Somehow i cant find a way, to implement this piece of code - or is there any better/easier implementation?

Thanks!

Edit: The Problem im facing is, that if i get more than just one "AttVector" back, my Code cant assign the second "AttVector". Therefore only the first calculation works, at the moment.

Upvotes: 0

Views: 398

Answers (2)

sbgib
sbgib

Reputation: 5828

Give all of the relevant <input> elements a common class, then it'd be easy to loop through them:

var inputs = document.getElementsByClassName("myclass");

for (i = 0; i < inputs.length; i++) {
  console.log(inputs[i].id);
}
<span class="hiddenAV">AV:</span><input type="text" class="myclass" id="AttVector" onfocusout="getBV()">
<span class="hiddenAC">/AC:</span><input type="text" class="myclass" id="AttComp" onfocusout="getBV()">
<span class="hiddenPR">/PR:</span><input type="text" class="myclass" id="PRReq" onfocusout="getBV()">

Upvotes: 2

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

CSS selectors are powerful enough for your need on their own. You can use a substring matching attribute selectors, a "starts with" syntax inspired by regexes : div[id^=AttVector]

Reads "Nodes of type div with an attribute id starting with "AttVector"

const elements = document.querySelectorAll("div[id^=AttVector]");
console.log(Array.from(elements));
<div id="AttVector1"/>
<div id="AttVector2"/>
<div id="AttVector3"/>
<div id="AttVector4"/>

Upvotes: 1

Related Questions