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
});
Related
I have a scenario like this:
for (var k in active) {
notifications.append(
'<a href="javascript:toast();">' +
'<div>' +
'<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
'</input>'+
'<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
'<span>' +
'<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
'<br/>' +
'<span class="time">Just Now</span>' +
'</span>' +
'</div>' +
'</input>'+
'</a>');
}
i created dynamic elements using jade template engine.
here i need to identify each <a> click and i nedd to get the value of hidden field.
function toast() {
var grade;
//var phone_number=document.getElementById('phone_number').value;
$.each($('.phone_number'), function () {
grade = $(this).val();
alert(grade);
});
}
by doing this i got a loop of value. which i didn't want. i need single item value. how to solve this ?
pass this to the toast
'<a href="javascript:toast(this);">' +
and change the toast method to
function toast( thisObj )
{
var grade = $( thisObj ).parent().find( '.phone_number[type="hidden"]' ).attr( "value" );
alert( grade );
}
notifications = $(".notifications")
active = [{ phone_number: "982334",expiry_count: "1"},
{ phone_number: "982334",expiry_count: "1"}]
var k;
for (var k in active) {
notifications.append(
'<a href="javascript:toast();">' +
'<div>' +
'<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
'</input>'+
'<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
'<span>' +
'<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
'<br/>' +
'<span class="time">Just Now</span>' +
'</span>' +
'</div>' +
'</input>'+
'</a>');
}
$(document).on('click', 'a', function(){
alert($(this).find('.phone_number').val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notifications"></div>
Its simple.Try this
$(document).on('click', 'a', function(){
alert($(this).find('.phone_number').val())
})
Send the toast function the k you are iterating over
'<a href="javascript:toast(' + k + ');">'
then use k in your function
function toast(k) {
//use k (maybe select by id)
}
i have json data which i want to display in html div using for loop. my control in entering in loop but not appending and displaying data in html div.
json data;
[{"id":"15","FirstName":"ranjan","MiddleName":"","LastName":"","Gender":"","Location":"r","Email":"ranjan.gupta.1994#gmail.com","Mobile":""},{"BookTitle":"","BookGenre":"","BookWriter":"","BookDescription":""}]
code;
$.getJSON(url, function(data) {
console.log(data);
if (data) {
alert("hey got the data" + JSON.stringify(data));
for (var i = 0; i < data.length; i++) {
alert("entered");
alert("hey got the data" + JSON.stringify(data[1]));
var $appendData =
$('<div id="' + data[i].id + '">' + '<p>'
+ 'FirstName:' + data[i].data.FirstName + '<br/>'
+ 'MiddleName:' + data[i].data.MiddleName + '<br/>'
+ 'LastName:' + data[i].data.LastName + '<br/>'
+ 'Gender:' + data[i].data.Gender + '<br/>'
+ 'Location:' + data[i].data.Location + '<br/>'
+ 'Email:' + data[i].data.Email + '<br/>'
+ 'Mobile:' + data[i].data.Mobile + '<br/>'
+ '</p>' + '</div>').appendTo('#postjson');
}
} else {
return;
}
// this is my div
</script>
<div class="grid" id="postjson"></div>
</div>
</div>
You got typo on your loop, just replace all your data[i].data.property with data[i].property
Javascript
$.getJSON(url,function(data) {
console.log(data);
if(data){
alert("hey got the data"+JSON.stringify(data));
for(var i=0; i<data.length; i++) {
alert("entered");
alert("hey got the data"+JSON.stringify(data[1]));
$('<div id="'+data[i].id+'">'
+'<p>'
+'FirstName:'+data[i].FirstName+'<br/>'
+'MiddleName:'+data[i].MiddleName+'<br/>'
+'LastName:'+data[i].LastName+'<br/>'
+'Gender:'+data[i].Gender+'<br/>'
+'Location:'+data[i].Location+'<br/>'
+'Email:'+data[i].Email+'<br/>'
+'Mobile:'+data[i].Mobile+'<br/>'
+'</p>'
+'</div>').appendTo('#postjson');
}
}
else {
return;
}
JsFiddle
I have this json data
somehow i displayed this part of data in html
and want to display this part of data
into div in html but i am unable to display it using for loop and don't to how to start each function from index 1 as index 0 in personal details data.
here is my code
var url = "http://localhost/ReadExchange/api.php";
$.getJSON(url, function(data) {
if (data) {
alert("hey got the data" + JSON.stringify(data));
var arr = data.length;
//$.each(data, function(i,element) {
var element = data[0];
$("#postjson").append(
'<div id="' + element.id + '">' + '<p>' + 'FirstName:' + element.FirstName + '<br/>'
+ 'MiddleName:' + element.MiddleName + '<br/>' + 'LastName:' + element.LastName + '<br/>' + 'Gender:' + element.Gender + '<br/>' + 'Location:' + element.Location + '<br/>' + 'Email:' + element.Email + '<br/>' + 'Mobile:' + element.Mobile + '<br/>' + '</p>' + '</div>'
);
for (var i = 1; i < arr; i++) {
$("#postjson").append(
'<div id="">' + '<p>' + 'BookTitle:' + data[i].data.BookTitle + '<br/>' + 'BookGenre:' + data[i].data.BookGenre + '<br/>' + 'BookWriter:' + data[i].data.BookWriter + '<br/>' + 'Gender:' + data[i].data.BookDescription + '<br/>'
+ '</p>' + '</div>'
);
}
} else {
return;
}
You can use Array.prototype.splice()
data.splice(0, 1);
then iterate data array at for loop, with i set to 0
var data = [{abc:123}, {def:456}];
data.splice(0, 1);
for (var i = 0; i < data.length; i++) {
alert(JSON.stringify(data))
}
I am having some problems while creating a dynamic webpage in javascript.
My idea is to read a list of events and people signed up on them. I create a page with all events (each event is a button) and clicking on one of them, see the list of users.
This works fine. But now, I am adding a button to export some of these users to an excel file. And I want to add a button with an onClick function like this:
...onclick=functionÇ(id_Event, numberOfUsers, listOfUsers)...
Inside of the html code generated by javascript. I found some problems also doing like this so I changed so:
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
I created a global array called arrayNumberUSersInEvents in which I am adding in each possition, people subscribed. i, is the id counter for each position.
But even this, I am getting an undefined while reading the value of the firsdt parameter. I think it is a problem of dynamic data, I am not executing the function I want to each time I click the button. Do you know how to do something like this?
To sum up: My problem is that I want to pass some arguments to a function in a dynamic created page. I don't know how to pass the data and read the correct parameters inside.
I added my code because one user asked for it:
for(i = 0; i < element.length; i++){
$(".eventsControl").append(
'<li id="listControl'+ element[i].id_Event +'">'+
'<a href="#EventControl' + element[i].id_Event + '"' + 'data-transition="slidedown">'+
'<img class="crop" src= "' + element[i].image + '" />'+
'<h2>' + element[i].name + '</h2>'+
'<p>' + "Desc: " + element[i].description +'</p>'+
'</a>'+
'</li>'
).listview('refresh');
//console.log(response);
//BUCLE for setting all users in each event. Better use some string and after, join all of them
header = ' <div width="100%" data-theme = "e" data-role="page" id='+ element[i].id_Event +
' data-url="EventControl' + element[i].id_Event + '"> ' +
' <div data-theme = "a" data-role="header"><h1>Lista de Asistencia</h1> ' +
' </div>'+
' <div data-role="content"> ' +
' <fieldset data-role="controlgroup" data-type="horizontal" style="text-align: center">' +
' <div style="width: 500px; margin: 0 auto;">';
//header = header + '<input data-theme = "c" onclick="saveExcelFunctionControl(this)" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
eval('var numberUsers' +element[i].id_Event + "=1");
arrayNumberUsersInEvents[i] = 0;
if(response.length>0){
bucle = ' <table width="100%" border="1" align="left"><tr>'+
' <th>Nombre</th>'+
' <th>Primer apellido</th>'+
' <th>Segundo apellido</th>'+
' <th>NIF</th>'+
' <th>Asistencia</th>'+
' </tr>';
for(iData = 0; iData < response.length; iData++){
if(element[i].id_Event == response[iData].id_Event){
//console.log(response[iData].name);
bucle = bucle + '<tr><td>'+ eval('numberUsers' +element[i].id_Event) +'</td><td>'+ response[iData].name +'</td><td>'+
response[iData].surname1 +'</td><td>'+
response[iData].surname2 +'</td><td>'+
response[iData].NIF + '</td>'+
'<td> '+
'<input type="checkbox" id="checkBox'+element[i].id_Event+'_'+iData+'" name="option'+iData+'" value="'+iData+'"> '+
'</td>'+
'</tr>';
eval('numberUsers' +element[i].id_Event + "++");
arrayNumberUsersInEvents[i] = arrayNumberUsersInEvents[i]+1;
}
}
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(\""element[i].id_Event "\","" + numberUsers + "\",\"" + response+ "\"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
//header = header + '<input data-theme = "a" onclick="saveExcelFunctionControl(""+numberUsers+"")" id="saveExcelControl' + element[i].id_Event + '" type="button" value = "Guardar a excel"></br>';
bucle = bucle + '</table>';
$("#controlList").after(header + bucle + '<div id=added'+element[i].id_Event+'></div>');
var td = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type","button");
input.setAttribute("value","Exportar a Excel CSV");
input.onclick = function() {
saveExcelFunctionControl(arrayNumberUsersInEvents[i], response);
};
td.appendChild(input);
document.getElementById("added"+element[i].id_Event).appendChild(td);
}
}
},
error: function(xhr, status, message) { alert("Status: " + status + "\nControlGetEventsRegister: " + message); }
});
You can use closure to pass parameters to dynamically created onclick handler:
input.onclick = (function() {
var arr = arrayNumberUsersInEvents[i];
var resp = response;
return function() {
saveExcelFunctionControl(arr, resp);
}
})();
How do JavaScript closures work?
var td = document.createElement("td");
var input = "<input type='button' value='Exportar a Excel CSV'";
input+= "onclick='saveExcelFunctionControl(""" +arrayNumberUsersInEvents[i]+""","""+ response+""");' />";
};
td.textContent=input;
document.getElementById("added"+element[i].id_Event).appendChild(td);
try this way
Well, I have a table with multiple text nodes I'm getting through the .text() function and linking to another table with one row that I'm using as a timeline.
I tried to input in a single td of the text values that corresponds to the correct data, but I only managed to grab the last value I in my loop, instead of getting them all. Here is my code:
var tHold, divLine, id, dataTitle, dataDescription;
$(".class1").each(function(){
tHold = $(this);
$(".class2").each(function(){
if ($(this).text() == tHold.attr("value")){
if($('#1').children("div#" + tHold.attr("name")).length == 0){
dataTitle = '<div class="r">' + $(this).text() + '</div><br/>';
dataDescription = '<div class="t">' + $(this).parent().children(".x").text() + ': ' + $(this).parent().children(".y").text() + ' (' + $(this).parent().children(".z").text() + ')' + '</div>';
divLine = $('<div id="' + tHold.attr("name") + '" class="b" value="' + tHold.attr("value") + '"></div>');
divLine.append(dataTitle);
divLine.append(dataDescription);
$("#1").append(divLine);
}
if($('#2').children("div#id" + tHold.attr("name")).length == 0){
dataTitle = '<div class="r">' + $(this).text() + '</div><br/>';
dataDescription = '<div class="t">' + $(this).parent().children(".x").text() + ': ' + $(this).parent().children(".y").text() + ' (' + $(this).parent().children(".z").text() + ')' + '</div>';
divLine = $('<div id="des' + tHold.attr("name") + '" class="c" value="' + tHold.attr("value") + '"></div>');
divLine.append(dataTitle);
divLine.append(dataDescription);
$("#2").append(divLine);
}
}
});
});
It's been simplified and cut out of a whole context , but all that matters is there. How can I set dataDescription to be multiple divs with diferent values instead of just the last I loop through?