1

I am trying to create a for loop that is equivalent to the the code below that way I don't have to type it all out each time.

var q1 = document.getElementById("q1").value;
var q2 = document.getElementById("q2").value;
var q3 = document.getElementById("q3").value;
var q4 = document.getElementById("q4").value;
var q5 = document.getElementById("q5").value;
google.script.run.AddRecord(q1, q2, q3, q4, q5);

I am particularly having a hard time declaring qi where i=1, 2, .., 5, so that way it doesn't think it's just a word or array. I have tried different things using string concatenation but can't get it to work (see started loop below). I feel like I am missing one little thing which is causing it to run into issues. I have seen different questions about this but can't get it to work.

for(var i=1; i<=5; ++i){
var "q"+i=document.getElementById("q"+i).value;
}
William Garske
  • 317
  • 1
  • 10

2 Answers2

2

You can use an array for this purpose. Declare an array and use i as an index to insert values in the array.

var markers = [];

for(var i=1; i<=5; ++i){
  markers[i] = document.getElementById("q"+i).value;
}
Hamad Javed
  • 106
  • 6
  • This is a good answer! I would use this. Remember arrays have been creating to handle sets of data. So if you want to access q1 its now markers[1]. – user1239299 May 31 '21 at 16:36
  • 1
    Exactly it will be accessible by array index like markers[0], markers[1], etc – Hamad Javed May 31 '21 at 16:37
2

You can push the values into an array and then use the spread operator to pass them to google.script.run.AddRecord

const elements = [];
for (let i = 1; i <= 5; i++) {
    elements.push(document.getElementById(`q${i}`).value);
}

google.script.run.AddRecord(...elements);
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26