AyeJay
AyeJay

Reputation: 459

JQuery - nested loop issue

I have created a javascript that runs when the user change the dropdown list (Note: the change function, and the way we get the value of the dropdown list work fine), I have tested the function multiple times and found the issue is my second For-loop I am really stuck wondering why it does not work.

$(document).ready(function(){
        var username = prompt("Please enter your Username", "default");
        console.log("User: ",username);

        $.ajax({ url : "/memory/intro",
                type: "POST",
                data: JSON.stringify({"username": username}),
                contextType: "text/json; charset=utf-8",
                success : function(){console.log("Done!");}});

        $("#lvl").change( function (){
                var diff = $(this).find("option:selected").attr('value');
                console.log(diff); //Personal testing
                console.log(typeof(diff)); //Personal testing
                for(var i=0; i < diff; ++i){
                        var row;
                        row = $("<tr></tr>");
                        for(var x=0; i < diff; ++x) {
                                var col;
                                col = $("<div></div>");
                                col.addClass("card");
                                col.data("col", x);
                                row.append(col);
                        }
                        $("#cards").append(row);
                };

        });

});

Note: If we comment the second for-loop the whole code works fine and we append the "tr" and "div" with the class name

Upvotes: 0

Views: 72

Answers (2)

AyeJay
AyeJay

Reputation: 459

Sadly I didn't realise that I had i < diff on the second loop, thanks to @nbrooks

Upvotes: 1

Nebulosar
Nebulosar

Reputation: 1855

second forloop try:

      for(var x=0; x < diff; ++x) {
            var col;
            col = $("<td></td>");
            col.addClass("card");
            col.data("col", x);
            row.append(col);
      }

So far as i know you shouldn't append a div to a tr, it causes errors (not js errors, but it are still markup errors)

check w3c validator if you want to be sure of this issue,

Upvotes: 0

Related Questions