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>');
}
}
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);
Ok, so, as was mentioned elsewhere, using .html() is just overriding the data each time. There are a couple issues in your code, however.
You are not properly closing your div(s) in the second loop.
You need to append the new data to the container (clear the container first if you need to, I do in my example.)
Fiddle
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);
// i'm emptying the containers, you may not need to depending
// on your implementation
$('#mainone').empty();
$('#maintwo').empty();
for(var j=0; j < test1.length; j++){
// use append here, not html
$('#mainone').append('<div id="' + test1[j] + '" class="well">' + test1[j] + '</div>');
}
for(var k=0; k<test2.length; k++){
// use append here, not html
// i also fix your markup ( you were not closing the div properly)
$('#maintwo').append('<div id="' + test2[k] + '" class="well">' + test2[k] + '</div>');
}
}
Related
I am using an .append to populate a div-id and all that works fine, i even get the loop inside, however i would like to make an item clickable inside the loop and load a div that holds details of that item. This is what i got so far.
<div id="GameContainer"></div>
var gamesData; //A global variable to hold Ajax response.
$.ajax({
type: 'Get',
url: "http://"URL/" + GamesList,
success: function (data) {
gamesData = data; // add the Ajax data to the global variable
var dynamic = "";
for (i = 0; i < data.length; i++) {
dynamic += '<div id="' + data[i].id_game + '" class="TopContainerCel" onclick="GameDetails(' + data[i] + ')">'
+ ' <div class="TopContainerCelBackground">'
+ ' <img class="TopContainerCelImage" src="' + data[i].CoverImage + '" />'
+ ' </div>'
+ ' <div class="TopContainerCelName">' + data[i].Name + '</div>'
+ ' </div>'
};
$('#GameContainer').append(''
+ '<div class="TopContainerScroll">'
+ dynamic
+ '</div>');
}
})
// based on the solution of K K [extended with an array.find]
added the global variable gamesData and filled it with the Ajax reponse
$(document).on("click", ".TopContainerCel", function () {
var elem = $(this);
console.log(elem[0].id) // the actual id clicked is there
console.log(gamesData) // all the data of the Ajax response is there
GameID = elem[0].id;
var gameData = gamesData[elem.data("id")]; // part that does not work
var gameData = gamesData.find(x => x.id_game == GameID); // works!
//gameData has the data
console.log(gameData)
});
So i found a diffent way of combining the two data together by using a find in the array. Is there a better way of doing this? If so why and what is the difference?
Try something similar to this:
var gamesData;//A global variable to hold Ajax response.
$.ajax({
type: 'Get',
url: "http://URL/" + GamesList,
success: function (data) {
gamesData = data;
var dynamic = "";
for (i = 0; i < data.length; i++) {
dynamic += '<div id="' + data[i].id_game + '" data-id="'+data[id]+'" class="TopContainerCel">'
+ ' <div class="TopContainerCelBackground">'
+ ' <img class="TopContainerCelImage" src="' + data[i].CoverImage + '" />'
+ ' </div>'
+ ' <div class="TopContainerCelName">' + data[i].Name + '</div>'
+ ' </div>'
};
$('#GameContainer').append(''
+ '<div class="TopContainerScroll">'
+ dynamic
+ '</div>');
}
})
$(document).on("click",".TopContainerCel",function(){
var elem = $(this);
var gameData = gamesData[elem.data("id")];
//gameData has your data
});
Note: The approach here is to store ajax response in a variable. From your code, the response is an array. So, when you iterate over the items, get the index of the clicked item in any way you prefer and access the detail of game using the index from gamesData.
you can add data-id to dynamic like : <div data-id="'+data[i].id+'".
then you can do :
var games = {};
for (i = 0; i < data.length; i++) {
games[data[i].id_game] = data[i];
dynamic += '<div id="' + data[i].id_game + '" class="TopContainerCel" onclick="GameDetails(' + data[i] + ')">'
+ ' <div class="TopContainerCelBackground">'
+ ' <img class="TopContainerCelImage" src="' + data[i].CoverImage + '" />'
+ ' </div>'
+ ' <div class="TopContainerCelName">' + data[i].Name + '</div>'
+ ' </div>'
};
$("#GameContainer").on('click','.TopContainerCel',function() {
var $this = $(this);
console.log(games[$this.data('id')])
// code logic here
});
Hi all I hope someone can help Im a bit stuck single developer on own , with the below what im trying to do is nest for loops, I have data back at the var = I; but not at the next two for statements, when the popup is called only the last record comes back I can see in console the data is there and the ids for the link and the data within do illicitate around , however only the last record appears I haven't uploaded the json because its a really long script any help on this would be very appreciated I have been playing with nested loops and got them to work just not in the bellow I normally use for/in apparently that's bad practice from what ive read up so changed to flat for loops.
<pre> $.getJSON('myurl', function (data) {
console.log(data);
var data = data.sponsor;
var output = "";
var myApp = new Framework7();
var $$ = Dom7;
output += "<ul>";
for (var i = 0; i < data.length; i++) {
output += "<li class='list-block media-list sponsors list-block-search '>";
output += "<div class='item-media-auto'>" + data[i].images + "</div>"; //working
output += "<div class='item-inner'>";
output += "<div class='item-title-row'>";
output += " <div id='name' class='item-title'>" + data[i].title + data[i].id +"</div>";
output += "</div>";
output += "<a href=" + data[i].custom['panaone_sponsorurl'] + " target='_blank'>";
output += data[i].custom['panaone_sponsorurl'];
output += "</a>";
output += ' <p>Create Popup</p>';
output += "</li>";
document.getElementById("placeholder").innerHTML = output;
output += "</ul>";
}
for (var l = 0; l < data.length; l++) {
$$('.create-popup'+ data[l].id).on('click', function () {
for (var j = 1; j < data.length; j++) {
var popupHTML = '<div class="popup '+ data[j].id + '">'+
'<div class="content-block ">'+
'<p>Popup created dynamically.'+ data[j].id + '</p>'+
'<p>Close me</p>'+
'</div>'+
'</div>'+
myApp.popup(popupHTML);
}
});
}
});
}
</pre>
I am having a problem with my for loop inside a javascript function. The variable i is not working as an argument for the function showAlbum(i). Why is that happening?
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td><a href=''onclick='showAlbum(i);' >"+
arr[i].artist +
" - " +
arr[i].title +
"</a></td></tr>";
}
out += "</table>";
Because i wrapped in quotations is the literal character i, not the value held within your i variable. You need to evaluate it outside of the quotations:
out += "<tr><td><a href=''onclick='showAlbum(" + i + ");' >"
The i is within the string literal, so variables are not parsed from the string.
Break out of the string like so:
out += "<tr><td><a href=''onclick='showAlbum(" + i + ");' >"+
// ^^^^^^^^^
Try changing the formatting to:
var i,
out = '<table>';
for (i = 0; i < arr.length; i++) {
out += '<tr><td><a href="" onclick="showAlbum(' + i + ')" >' +
arr[i].artist +
' - ' +
arr[i].title +
'</a></td></tr>';
}
out += '</table>';
Just wondering if anyone can help me.
I have created a table, and using Javascript I am extracting all the data and placing it into divs.
$(function () {
$('table').each(function () {
var output = "",
table = $(this),
rowHead = table.find('tbody tr th'),
rowSubject = table.find('thead tr th:not(:first-child)'),
rowContent = table.find('tbody tr td'),
copy = table.clone();
output += '<div class="mobiled-table">';
for (i = 0; i < rowHead.length; i++) {
output += '<div class="head">' + $(rowHead[i]).html() + '</div>';
for (j = 0; j < rowSubject.length; j++) {
output += '<div class="subject">' + $(rowSubject[j]).html() + '</div>';
output += '<div class="content">' + $(rowContent[i]).html() + '</div>';
}
}
output += '</div>';
$('table').append(output);
});
});
It all works great except the .content class isnt working correctly. I believe I am using the wrong 'for loop' or I need to create another 'for loop'. Please take a look at my codepen and you will see my problem
http://codepen.io/anon/pen/JrKBf
I hope someone can help.
Because rowContent contains the matrix of cells but as a one dimension array, you have to translate (i, j) to a valid index for rowContent which is (i * 4) + j:
rowContent[i]
should be replaced by:
rowContent[(i*4) + j]
In a simpler way, you can do like this,
var container=$("#container");
$("table tr:not(:first)").each(function() {
var heading = $(this).find("th").html();
container.append('<div class="subject">' + heading + '</div>');
$(this).find("td").each(function(i) {
container.append('<div class="subject">' + $("table th").eq($(this).index()).html() + '</div>');
container.append('<div class="content">' + $(this).html() + '</div>');
});
});
Fiddle
I created an array of strings, with the format "monthX" where is a number that increases throughout the array.
I have a function where I'm trying to reference a specific item of the array, but it keeps coming in as undefined. Here's my code:
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
The area I'm interested in is that "monthList[3]" line. That keeps coming in as undefined, even though I console.log(monthList[3]) it correctly says "month6". Any ideas? Do I have bug in my code?
Well, two questions:
WHEN do you call "listCategories()" ?
before or after you set monthList?
And, have you set the global for monthList first?
//globalize monthList array to be usable in functions
var monthList;
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
//do NOT CALL listCategories prior this line!!
That should do
In the code you show us, you never declare monthList or define it as an array.
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
var monthList = [],
startingMonth = 1;
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
Notice the additional lines I added after the function definition, but before the loop.