Iterate through JSON and get image for each data key - javascript

I have this table
<table id="player_info">
<tr>
<th>Position</th>
<th>Club</th>
<th>Points</th>
<th>Matches Played</th>
<th>Wins</th>
<th>Draws</th>
<th>Losses</th>
<th>Goals For</th>
<th>Goals Against</th>
<th>Goal Difference</th>
<th>Form</th>
</tr>
</table>
And I have this function which iterates through JSON keys and creates a new table cell with each key. I would like to have the logo of each club appear next to its name in the table cell. The logo URL is stored in the JSON.
My current code
data.api.standings[0].forEach(elements => {
var tr = document.createElement('tr');
var img = new Image();
img.src = elements.logo;
tr.innerHTML = '<td>' + elements.rank + '</td>' +
'<td>' + elements.teamName + img + '</td>' +
'<td>' + elements.points + '</td>' +
'<td>' + elements.all.matchsPlayed + '</td>' +
'<td>' + elements.all.win + '</td>' +
'<td>' + elements.all.draw + '</td>' +
'<td>' + elements.all.lose + '</td>' +
'<td>' + elements.all.goalsFor + '</td>' +
'<td>' + elements.all.goalsAgainst + '</td>' +
'<td>' + elements.goalsDiff + '</td>' +
'<td>' + elements.forme + '</td>';
table.appendChild(tr);
});
However I am getting the team name and [object HTMLImageElement] and no image.

In your case you can do this instead
var img = '<img src="' + elements.logo + '" />'
instead of making an img element

Related

How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))?

How do I access the value of a td (x3) of the same tr (x1), if I click on the tr (x1 of td (x2))?
$(document).ready(function () {
$.ajax({
url: '/api/Usuario/GetPermisosRolPorUsuario',
method: 'GET',
dataType:'JSON',
data: { NitEmpresa,NombreUsuario },
headers: {
'Authorization': 'Bearer '
+ sessionStorage.getItem("accessToken")
},
success: function (data) {
debugger
$('#tblBody').empty();
$.each(data, function (index, value) {
var row =
$('<tr>'
+'<td id="IdUsuario">'+ value.IdUsuario + '</td>'
+ '<td id="RolId">' + value.RolId + '</td>'
+ '<td id="Estado" >' + value.Estado + '</td>'
+ '<td>' + value.Rol + '</td>'
+ '<td>' + value.DescripcionRol + '</td>'
+ '<td>' + value.NombreUsuario + '</td>'
+ '<td>' + value.FullName + '</td>'
+ '<td>' + value.licenciaEmpresa + '</td>'
+ '<td>' + value.RazonSocial + '</td>'
+ '<td>' + value.NitEmpresa + '</td>'
+ '<td>' + value.Correo + '</td>'
+ '<td>' + value.Celular + '</td>'
+ '<td>' + formatDate(value.licenciaFechaExpire) + '</td>'
);
$('#tblData').append(row);
});
Thank you, I managed to access the brothers 'td', as follows:
$('tr td:nth-child(3)', '#tblData').click(function () {
returns to the father to look for his brothers
var $thisRow = $(this).closest('tr')
brothers td
IdUsuario = $('td:first', $thisRow).text();
RolId = $('td:nth-child(2)', $thisRow).text();
Estado= $('td:nth-child(3)', $thisRow).text();
//an alert to print the values
alert(IdUsuario + '-' + RolId + '-' + Estado);
});
},
error: function (jQXHR) {
toastr.error('Sistemas Infinitos Informa: '+jQXHR.responseText);
}
});
});
$.each(data, function (index, value) {
var row =
$('<tr>'
+'<td id="IdUsuario">'+ value.IdUsuario + '</td>'
+ '<td id="RolId">' + value.RolId + '</td>'
+ '<td id="Estado" >' + value.Estado + '</td>'
First, each element in the DOM should have a unique id. By repeating the same ID multiple times, I'm not sure your on('click') events will attach in all browsers and return the value you are looking for. Instead, your click event should look something like this:
$('tr', '#tblData').click(function () {
var id1 = $('td:first-child', this).text();
var id2 = $('td:nth-child(2)', this).text();
var id3 = $('td:nth-child(3)', this).text();
...
}
or if you only want to allow clicking on the first TD:
$('tr td:first-child', '#tblData').click(function () {
var $thisRow = $(this).closest('tr')
var id1 = $(this).text();
var id2 = $('td:nth-child(2)', $thisRow).text();
var id3 = $('td:nth-child(3)', $thisRow).text();
...
}

how to append value in td

I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in <td>. I also try to gave gave td an id e.g <td id="files">
here is my code:
function format(d) {
var str = d.files;
var myarr = str.split(",");
for (var i = 0; i < myarr.length; i++) {
alert(myarr[i]);
$("#files").append("<a href='/uploads/" + myarr[i] + "'>" + myarr[i] + "</a>");
}
// `d` is the original data object for the row
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr>' +
'<tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr>' +
'<tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr>' +
'<tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr>' +
'<tr>' +
'<td>Files:</td>' + '<td id="files">'
'</td>' +
'</tr>' +
'</table>';
}
I hope it will be a easy fix.any help will be highly appreciable
Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:
function format(d) {
var str = d.files;
var filesHtml = str.split(",").map(function(file) {
return '' + file + '';
});
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr><tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr><tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr><tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr><tr>' +
'<td>Files:</td>' +
'<td id="files">' + filesHtml + '</td>' +
'</tr>' +
'</table>';
}
var html = format({
person: 'John Smith',
phone: '1234 567890',
web: 'http://google.com',
ttype: 'Foobar',
files: 'a.jpg,b.jpg'
});
$('div').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

jQuery creating tables, but currently keeps repeating the table under the previous one when submit button is clicked

my jQuery creates tables, but currently it keeps repeating the new tables under the previous ones when 'submit' button is clicked. How do I toggle it so it clears the previous table before showing the new table?
Any help would be great thanks!
<script type="text/javascript">
function call_everybody(){
display_results_table();
display_cyclist_results_table();
display_cyclist2_results_table();
}
function display_results_table() {
$("medal_table").empty();
$('<table id = "results_table">').appendTo('#medal_table');
$.get("sam2.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (results_obtained) {
$('<tr><td>Rank</td>' +
'<td>Country Name</td>' +
'<td>Population</td>' +
'<td>GDP</td>' +
'<td>Gold</td>' +
'<td>Silver</td>' +
'<td>Bronze</td>' +
'<td>Total</td></tr>').appendTo('#results_table');
for (var i = 0; i <= results_obtained.length; i++) {
$('<tr><td>' + (i+1) + '</td>' +
'<td>' + results_obtained[i].country_name + '</td>' +
'<td>' + results_obtained[i].population + '</td>' +
'<td>' + results_obtained[i].gdp + '</td>' +
'<td>' + results_obtained[i].gold + '</td>' +
'<td>' + results_obtained[i].silver + '</td>' +
'<td>' + results_obtained[i].bronze + '</td>' +
'<td>' + results_obtained[i].total + '</td></tr>').appendTo('#results_table');
}
},'json');
$('</table>').appendTo('#medal_table');
}
function display_cyclist_results_table() {
$("cyclist_table").empty();
$('<table id = "cyclist_results_table">').appendTo('#cyclist_table');
$.get("sam3.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist_results_table');
for (var j = 0; j <= cyclist_results_obtained.length; j++) {
$('<tr><td>' + cyclist_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist_results_obtained[j].name + '</td>' +
'<td>' + cyclist_results_obtained[j].gender + '</td>' +
'<td>' + cyclist_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist_results_table');
}
},'json');
$('</table>').appendTo('#cyclist_table');
}
function display_cyclist2_results_table() {
$("cyclist2_table").empty();
$('<table id = "cyclist2_results_table">').appendTo('#cyclist2_table');
$.get("sam4.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist2_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist2_results_table');
for (var j = 0; j <= cyclist2_results_obtained.length; j++) {
$('<tr><td>' + cyclist2_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist2_results_obtained[j].name + '</td>' +
'<td>' + cyclist2_results_obtained[j].gender + '</td>' +
'<td>' + cyclist2_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist2_results_table');
}
},'json');
$('</table>').appendTo('#cyclist2_table');
}
</script>
<title>sam.php</title>
</head>
<body>
<form name="form">
<table>
<tr><td><input name="Country_1" id="Country_1" value="GBR" type="text"></td></tr>
<tr><td><input name="Country_2" id="Country_2" value="USA" type="text"></td></tr>
<td><input id='toggle' type="button" value="Cyclist Comparison" onclick="call_everybody()"/></td></tr>
</table>
</form>
<div id = "toggle_table">
<div id="medal_table"></div>
<div id="cyclist_table"></div>
<div id="cyclist2_table"></div>
</div>
</body>
You need to add -
$('#results_table').remove();
Prior to -
$('<table id = "results_table">').appendTo('#medal_table');

Add class to html element dynamic

I'm building a dynamic table in html with javascript. Here is a piece of the javascript code.
var tr = $('<tr/>');
$(tr).append('<td>' + p1 + '</td>');
$(tr).append('<td>' + p2 + '</td>');
$(tr).append('<td>' + p3 + '</td>');
$(tr).append('<td>' + p4 + '</td>');
$(tr).append('<td>' + item.status + '</td>');
$(tr).append('<td><button class=\"btn\" onclick=\"join(' + item.gameId + ');\">Join</button></td>');
$('tbody').append(tr);
I want to add a class (either 'error' or 'success') to the row element.
I tried
tr.className = "success";
This didn't work.
Just use
tr.addClass("success")
You're caching your jquery elem in var tr so there's no reason to call $(tr) just use tr
This should work:
$(tr).addClass("success");
It seems you're using jQuery, you should try using: $(tr).addClass('success')
Also you're doing too many unnecessary appends, you could optimize your code to:
var tr = '<tr><td>' + p1 + '</td>' +
'<td>' + p2 + '</td>' +
'<td>' + p3 + '</td>' +
'<td>' + p4 + '</td>' +
'<td>' + item.status + '</td>' +
'<td><button class=\"btn\" onclick=\"join(' +
item.gameId +
');\">Join</button></td></tr>';
$('tbody').append(tr);

how to repeat the rows dynamically in .html() jqueryajax

In the below code am having one table with values from database.After executing the the query if am having 5 values am getting only the first value in my table(inside pop up).in this html() function how can i add the foreach and type of parametrs for for each,
i used ajax,json,jquery
My code is;
success: function (msg) {
var data = $.parseJSON(JSON.stringify(eval("(" + msg.d + ")")));
$('<div></div>')
.appendTo('body')
.html('<div><b>SHAREHOLDER DETAILS</b></br>' + data.Id + '</div>' +
'<div>' + data.name + '</div>' +
'<div>' + data.Id + '</div>' +
'<table border="1" style="background-color:silver;"><tr>' +
'<td>' + 'OwnedBy' + '</td>' +
'<td>' + 'ShareClass' + '</td>' +
'<td>' + 'EffectiveInterest' + '</td>' +
'<td>' + 'DeemedInterest' +'</td>' +
'<td>' + 'SharesOwned' + '</td>' +
'<td>' + 'SharesIssued' + '</td>' +
'</tr>' +
'<tr>' +
'<td>' + data.Id +'</td>' +
'<td>' + data.share + '</td>' +
'<td>' + data.effect + '</td>' +
'<td>' + data.deemed + '</td>' +
'<td>' + data.owned + '</td>' +
'<td>' + data.issued + '</td>' +
'</tr>' +
'</table>')
.dialog({
modal: true,
title: '<div>' + data.Id + '</div>',
zIndex: 10000,
autoOpen: true,
position: ['right', 'top'],
width: 'auto',
height: 'auto',
modal: false,
resizable: false,
closeOnEscape: false,
show: "slide",
hide: "explode",
close: function (event, ui) {
$(this).remove();
}
});
},
I don't know how much effort you've put into solving this on your own, but in the interest of fairness, I'll explain the thought process a bit. What you need to consider is conceptualizing and separating the "rows" from the "general entity", eg, "I have a table with rows which contain data".
The loop itself runs when creating the rows, and has to be performed as a separate action from creating the table itself. Even if you embed the loop logic into the table construction itself (as far as the markup generation itself goes, which I consider bad practice), you still have to consider each row as the result of a loop run, distinct from the table, thead, and tbody. Note, even with the rows (tr), you have another (potential) loop requirement in each cell in the row (td). In this case you don't need a loop at that level, but that points to conceptualizing the rudiments of loop design and utilization.
Here is a method using jQuery element caching and a jQuery.each() loop, which is a type of foreach loop. Note, in Javascript there is no dedicated foreach loop; there is, however, for(var i in object), which allows you to iterate over an object of this kind.
$(document).ready(function(){
var $table = $('<table>'),
$tbody = $('<tbody>'),
$thead = $('<thead>' +
'<tr>' +
'<th>OwnedBy</th>' +
'<th>ShareClass</th>' +
'<th>EffectiveInterest</th>' +
'<th>DeemedInterest</th>' +
'<th>SharesOwned</th>' +
'<th>SharesIssued</th>' +
'</tr>' +
'</thead>'),
$tr = $('<tr>'),
data = {
grp1: {
Id: 'id1',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
},
grp2: {
Id: 'id2',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
},
grp3: {
Id: 'id3',
share: 'share',
deemed: 'deemed',
effect: 'effect',
owned: 'owned',
issued: 'issued'
}
};
$table
.append($thead, $tbody)
.appendTo(document.body);
jQuery.each(data, function(i, val) {
$tr.clone()
.appendTo($tbody)
.append(
'<td>' + val.Id +'</td>' +
'<td>' + val.share + '</td>' +
'<td>' + val.effect + '</td>' +
'<td>' + val.deemed + '</td>' +
'<td>' + val.owned + '</td>' +
'<td>' + val.issued + '</td>'
);
});
});
http://jsfiddle.net/YFwTe/
You need some sort of iterator function, as you have it the code will only pull the first value.
My suggestion would be to use .each:
var element = $('<table></table>').appendTo('body');
jQuery.each(data, function(i, val) {
element.append(
'<tr>' +
'<td>' + val.Id +'</td>' +
'<td>' + val.share + '</td>' +
'<td>' + val.effect + '</td>' +
'<td>' + val.deemed + '</td>' +
'<td>' + val.owned + '</td>' +
'<td>' + val.issued + '</td>';
'</tr>';
);
});
Haven't tested it just because I don't have a data string, but hopefully that gets you close.

Categories

Resources