Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.forEach loop: use variable

I'm looping through a set of 16 ids and assigning an eventListener to each one. I want to send a number to my php file (1 for the first id, 2 for the second, etc, etc), but it seems that i is more dynamic than I'd like it to be. Every id sends 17.

klasses.forEach(function(klass){
    var svgElement = svgDoc.getElementById(klass); //get the inner element by id
    svgElement.addEventListener("mouseup",function(){
        $.ajax({
            type: "POST",
            url: "buildService.php",
            data: { "service" : i}
        }).done(function(msg){
            alert(lameArray[i]);
            $("#modalSpan").html(msg);
            $("#modmodal").modal();
        });
    });
    i++;
});

How can I set each one to a specific number? I've also tried:

var lameArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
...
data: { "service" : lameArray[i]}
like image 539
SomeKittens Avatar asked Dec 16 '22 21:12

SomeKittens


1 Answers

What's i? The problem is that i is a global variable, or a variable outside the forEach cycle anyway, so when the mouseup event is triggered, the value of i in that istant is used, and not the one it had when the event listener is defined.

Mind you, since you're using forEach, that the callback function actually is called with a second parameter, which is the counter. So you can use:

klasses.forEach(function(klass, i) {
    ...
});

Now, i is a variable in the forEach scope, and serves your purposes. (forEach calls the callback function with a third parameter too, that is the collection itself - klasses in your case.)

Note: since you're using jQuery, you should code with a more "jQuery-like" style. So change your code in something like this:

$.each(klasses, function(i, klass) {
    $("#" + klass).mouseup(function(){
        $.ajax({
            type: "POST",
            url: "buildService.php",
            data: {service: i + 1}
            ...
        });
    });
});
like image 102
MaxArt Avatar answered Dec 22 '22 00:12

MaxArt