Ad

Not Able To Display The Div Content In Two Container

- 1 answer

I want to display the randomly displayed values from 'test1' and 'test2' arrays into two different containers "mainone" and "maintwo". Now I am able to get the random values from array but failed to display the whole html content in containers during on click of click me button each time;

My fiddle here:

https://jsfiddle.net/scrumvisualize/yecoqusp/

Page with data on load

var teama = ["one_1", "one_2", "one_3","one_4", "one_5"];
var test1 = [];
var test2 = [];
function startTeam(){
    for(var i = teama.length - 1; i >= 0; i--){
        var randomIndex =Math.floor(Math.random()*teama.length);
        var rand = teama[randomIndex];
        teama.splice(randomIndex, 1);
        if(i%2){
            test1.push(rand);
        }else{
            test2.push(rand);
        }
    }
    alert(test1);
    alert(test2);

    for(var j=0; j<test1.length; j++){
        $('#mainone').html('<div id="' + test1[j] + '" class="well">' + test1[j] + '</div>');
    }

    for(var k=0; k<test2.length; k++){
        $('#maintwo').html('<div id="' + test2[k] + '" <div class="well"></div>' + test2[k] + '</div>');
    }
}
Ad

Answer

I tried to work on your fiddle, but no avail, as a guesswork, you have this

for(var j=0; j<test1.length; j++){
    $('#mainone').html('<div id="' + test1[j] + '" class="well">' + test1[j] + '</div>');
}
for(var k=0; k<test2.length; k++){
    $('#maintwo').html('<div id="' + test2[k] + '" <div class="well"></div>' + test2[k] + '</div>');
}

each loop in the two for-loops is overriding the corresponding div's html, instead create two variables, say main1html and main2html outside the for loops and the for-loops should be something like:

for(var j=0; j<test1.length; j++){
    main1html += '<div id="' + test1[j] + '" class="well">' + test1[j] + '</div>');
}
for(var k=0; k<test2.length; k++){
    main2html += '<div id="' + test2[k] + '" <div class="well"></div>' + test2[k] + '</div>';
}

and after the two for-loops assign the final html to both divs, like this:

$('#mainone').html(main1html);
$('#maintwo').html(main2html);
Ad
source: stackoverflow.com
Ad