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

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.

Related

Pulling data with spaces in json [duplicate]

This question already has answers here:
Access JSON output with spaces
(4 answers)
Closed 3 months ago.
I can't extract the data with spaces in the area that I have shown with the red pen, how can I do this?
$.ajax({
url: "../api/api.php",
type: "POST",
data: {
tc: $("#tcx").val(),
},
success: (res) => {
if (res) {
var json = JSON.parse(res);
$('tbody').html("");
$.each(json, function(key, value) {
$('tbody').append('<tr>' +
'<td>' + value.YAKINLIK + '</td>' +
'<td>' + value.TC + '</td>' +
'<td>' + value.ADI + '</td>' +
'<td>' + value.SOYADI + '</td>' +
'<td>' + value.DOGUM TARIHI + '</td>' +
'<td>' + value.NUFUS IL + '</td>' +
'<td>' + value.NUFUS ILCE + '</td>' +
'<td>' + value.ANNE ADI + '</td>' +
'<td>' + value.ANNE TC + '</td>' +
'<td>' + value.BABA ADI + '</td>' +
'<td>' + value.BABA TC + '</td>' +
'</tr>');
});
} else {
alert("Hata oluştu!");
return;
}
},
error: () => {
alert("Hata oluştu!");
}
});
}
I tried to parse but without success
enter image description here
If you're just trying to read out the value from an object, based on a key that has spaces in it, you can use this syntax:
const myObject = { withoutSpaces: 1, "with spaces": 2 };
const valueOne = myObject.withoutSpaces;
const valueTwo = myObject["with spaces"];
So in your case you want to use something like:
value["DOGUM TARIHI"]

If not empty or null in JS return function

I have Javascript function and I want to check multiple if statements in return.
If the value exist or is not null then it should return a row with information,
I am not sure how to do this, I am thinking something like this, E.g:
function format(d){
return '<table cellpadding="5" cellspacing="0" border="0">' +
if (name) {
'<tr>' +
'<td>Name:</td>' +
'<td>' + d.name + '</td>' +
'</tr>' } +
if (place)
'<tr>' +
'<td>Place:</td>' +
'<td>' + d.place + '</td>' +
'</tr>' } +
if (date) {
'<tr>' +
'<td>Date:</td>' +
'<td>' + d.date + '</td>' +
'</tr>' } +
'</table>';
}
Like Daniel pointed out, you could build the string on your way out like this:
function myFormat(d) {
let result = '<table cellpadding="5" cellspacing="0" border="0">';
if (name){
result += '<tr>' + '<td>Name:</td>' + '<td>' + d.name + '</td>' + '</tr>';
}
if (place){
result += '<tr>' + '<td>Place:</td>' + '<td>' + d.place + '</td>' + '</tr>';
}
if (date){
result += '<tr>' + '<td>Date:</td>' + '<td>' + d.date + '</td>' + '</tr>';
}
result += '</table>';
return result;
}
Html elements could be combined together as well to make it simpler like this:
'<tr><td>Place:</td><td>' + d.name + '</td></tr>'
I see that you can create a template for row. Why not to use a separate function:
formatRow(value, label)
'formatRow' function can use if statement to check if value is empty and decide to return a row or empty string for concatenation.
function formatRow(value, label){
if(value) {
return '<tr>' +
'<td>' + label + '</td>' +
'<td>' + value + '</td>' +
'</tr>';
}
return '';
}
Then run it within format() function for each property that you want to use.
function createCell(text){
const td = document.createElement('td');
td.textContent=text;
return td
}
function createRow(data, key){
row = document.createElement('tr');
row.appendChild(createCell(key[0].toUpperCase() + key.substring(1) + ':' ))
row.appendChild(createCell(data[key]))
return row;
}
function format(d){
table = document.createElement('table');
table.setAttribute("cellpadding", "5");
table.setAttribute("border", "0");
table.setAttribute("cellspacing", "0");
Object.keys(d).forEach(key => table.appendChild(createRow(d, key)))
return table
}
document.body.appendChild(format({data: '5 feb 2021', name: 'John', place: 'New York' }))
document.write('<hr>')
document.body.appendChild(format({data: '5 feb 2021', name: 'John' }))
document.write('<hr>')
document.body.appendChild(format({data: '5 feb 2021' }))

Iterate through JSON and get image for each data key

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

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>

Categories

Resources