Marcel Marcel - 1 year ago 48
Javascript Question

A loop within a loop - Javascript

I have a problem with a loop inside a loop.

By selecting the number and clicking the "Generate boxes" button it generates boxes with numbers from 1 to 49.
If you click the first time everything works fine.
But if you add more boxes it once again adds those 49 numbers to the already existing boxes. That's the problem. I only want to generate new boxes with numbers from 1 to 49.

This is the code:

function kasterl() {
$(".plunder").click(function() {
var wert = $( "#wieviel option:selected").text();
MyInt = parseInt(wert);

function createKaesten(zahl) {
var gesamt = $(".kasten").length+1;
var numberOf = $(".kasten").length;

for(var i=1; i<=zahl; i++) {
$(".rahmen").append("<div class='kasten nr"+ gesamt +"'><ul></ul></div>");

for(var n=1; n<=49; n++) {
$(".kasten ul").append("<li class='nummer'>" + n + "</li>");

And here you can test it: link for testing

Answer Source

As you have found, $(".kasten ul").append(...) will append to all elements that matched the ".kasten ul" selector.

You said you had a problem with a "loop within a loop", but your current code doesn't in fact nest the loops. Following is a solution that actually does nest the loops:

function createKaesten(zahl) {
  var gesamt = $(".kasten").length + 1;
  var numberOf = $(".kasten").length;
  var newUL;

  for (var i = 1; i <= zahl; i++) {
    newUL = $("<ul></ul>");
    for (var n = 1; n <= 5; n++) {                       
      newUL.append("<li class='nummer'>" + n + "</li>");
    $("<div class='kasten nr" + gesamt + "'></div>").append(newUL).appendTo(".rahmen");

$("button").click(function() {
li { display: inline-block; padding: 0 10px; }
.kasten { border: thin black solid; margin: 2px; padding: 0px; }
<script src=""></script>
<div class="rahmen"></div>

The outer loop creates a new, empty UL, then the inner loop appends the new LI items to that UL, then we create a DIV, append the new UL to it, then append the DIV to the .rahmen" container.

(Note that for demo purposes each click of the button only adds 3 x 5 items, rather than something x 49 items, and I've styled the LIs to go across the page horizontally so that it's easier to see what's happening. Click "Run code snippet" to try it out.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download