Do it like this:
Use let
for the variable i
in the for
block, so it is a separate variable that can still be referenced when the loop has completed and you are only then getting the responses from the get
calls
Use +
to convert val()
to a number (although in your case it is not absolutely necessary, since the multiplication with the the conversion on-the-fly)
Code:
$("#sendeS1").click(function () {
var Q_Values = [];
var G_Values = [];
var R_Values = [];
for(let i = 1; i <= 20; i++){
$.get("bewertung/get/weight/"+i, function (weight) {
Q_Values[i-1] = +$('#startup_1').find('.'+i).val();
G_Values[i-1] = weight;
R_Values[i-1] = Q_Values[i-1] * G_Values[i-1];
console.log("Q:"+Q_Values);
console.log("G:"+G_Values);
console.log("R:"+R_Values);
});
//...etc
Warning: the arrays will not yet have values when the for
loop has completed, so don't assume you have all data right after the loop. See How do I return the response from an asynchronous call? on several ways to deal with that.
One way that is not the nicest code, but the easiest to understand, is to use a count down, so you know when you have all data, and then call a function that will do the further processing:
$("#sendeS1").click(function () {
var Q_Values = [];
var G_Values = [];
var R_Values = [];
var countDown = 20;
for(let i = 1; i <= 20; i++){
$.get("bewertung/get/weight/"+i, function (weight) {
Q_Values[i-1] = +$('#startup_1').find('.'+i).val();
G_Values[i-1] = weight;
R_Values[i-1] = Q_Values[i-1] * G_Values[i-1];
console.log("Q:"+Q_Values);
console.log("G:"+G_Values);
console.log("R:"+R_Values);
countDown--;
if (countDown == 0) processResults(Q_Values, G_Values, R_Values);
});
//...etc
But I would really advise to look into Promises. That really is the way to go. Luckily jQuery $.get
returns a promise, and those promises can be passed to $.when
, which will call its then
method when all these promises have been fulfilled. (See also What does $.when.apply($, someArray)
do?).
$("#sendeS1").click(function () {
var Q_Values = [];
var G_Values = [];
var R_Values = [];
var promises = [];
for(let i = 1; i <= 20; i++){
promises.push($.get("bewertung/get/weight/"+i, function (weight) {
Q_Values[i-1] = +$('#startup_1').find('.'+i).val();
G_Values[i-1] = weight;
R_Values[i-1] = Q_Values[i-1] * G_Values[i-1];
console.log("Q:"+Q_Values);
console.log("G:"+G_Values);
console.log("R:"+R_Values);
}));
//...etc
}
$.when.apply($, promises).then(function() {
// all is done, process the results here ...
});
This code could be further improved so that each promise would resolve to its own value, and not yet push the product into an array, but that is something you can maybe look into yourself as an exercise.