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);
Related
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))?
$(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();
...
}
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>
I'm stucked in a situation now, i need to replace grand_score with paper_score + final_score (i.e the sum of paper_score and final_score). I've tried different alternations but still no fruitful result. please help me.
'<td>' + result['records'][i]['paper_score'] + '</td>' + //continuous assessment
'<td>' + result['records'][i]['final_score'] + '</td>' + //examination
'<td>' + result['records'][i]['grand_score'] + '</td>' + //ca + exam
You can simply use the + operator to add them together:
'<td>' + result['records'][i]['paper_score'] + '</td>' + //continuous assessment
'<td>' + result['records'][i]['final_score'] + '</td>' + //examination
'<td>' + (result['records'][i]['paper_score'] + result['records'][i]['final_score']) + '</td>' + //ca + exam
If paper_score and final_score are strings instead of numbers, you'll need to cast them first (assuming floats here, you could also use parseInt() for whole numbers):
'<td>' + (parseFloat(result['records'][i]['paper_score']) + parseFloat(result['records'][i]['final_score'])) + '</td>' + //ca + exam
i have this code:
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr><td>' + data.times[i].destination.name + '</td><td id="appendLate' + i + '">' + time + '</td><td>' + data.times[i].track + '</td><td>' + data.times[i].train_type + '</td><td>' + data.times[i].company + '</td></tr>'
// laat vertragingen zien (BETA)
if (data.times[i].delay / 60 >= 1) {
$('#appendLate' + i + '').append("+" + data.times[i].delay / 60).addClass("late");
}
}
table.html(tableContent);
}
The if statement appends stuff and adds a class. i know it wont work like this.. but i cant seem to get how it WIL work.. Can some one help?
See it live: http://codepen.io/shiva112/pen/JGXoVJ?editors=001
Well, you're basically almost there. The right way to do it is to build the entire string before doing any DOM manipulation, since DOM operations are very slow (relatively).
Let's say your index.html looks like:
<html>
<head>
<title>Cool site!</title>
</head>
<body>
<table id="myCoolTable"></table>
</body>
</html>
Then your JavaScript simply becomes:
var tableContent = '';
for (var i = 0; i < data.times.length; ++i) {
var time = formatTime(data.times[i].time);
tableContent += '<tr>'
+ '<td>' + data.times[i].destination.name + '</td>';
if (data.times[i].delay / 60 >= 1) {
tableContent += '<td id=\'appendLate\'' + i + ' class=\'late\'>' + time + '</td>' + '+' + (data.times[i].delay / 60);
} else {
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>';
}
tableContent += '<td id=\'appendLate\'' + i + '>' + time + '</td>'
+ '<td>' + data.times[i].track + '</td>'
+ '<td>' + data.times[i].train_type + '</td>'
+ '<td>' + data.times[i].company + '</td>'
+ '</tr>';
}
$('#myCoolTable').html(tableContent);
What this does is build the HTML for the entire table. Then update the table only once. Hope it helps!