I have a little issue with my For loop in Javascript. Here is my code:
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
var tr;
for (var i = 0; i < json.messages.length; i++) {
tr = $('<tr/>');
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
tr.append("<td>" + details.signals[j].start_bit + "</td>");
tr.append("<td>" + details.signals[j].comment + "</td>");
tr.append("<td>" + details.signals[j].bit_length + "</td>");
tr.append("<td>" + details.signals[j].factor + "</td>");
tr.append("<td>" + details.signals[j].offset + "</td>");
tr.append("<td>" + details.signals[j].is_big_endian + "</td>");
tr.append("<td>" + details.signals[j].is_signed + "</td>");
tr.append("<td>" + details.signals[j].name + "</td>");
$('#table_1').append(tr);
}
}
});
});
I declare a table-row (tr). I use it each time I loop through my json file. The problem is that I get one single row with all the data.
I would like to cut the row in order to have a readable table.
Look at the snapshot : .
This is happening because you're only creating one <tr> per table.
Create your trs inside the inner loop:
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
var tr;
for (var i = 0; i < json.messages.length; i++) {
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
tr = $('<tr/>');
tr.append("<td>" + details.signals[j].start_bit + "</td>");
tr.append("<td>" + details.signals[j].comment + "</td>");
tr.append("<td>" + details.signals[j].bit_length + "</td>");
tr.append("<td>" + details.signals[j].factor + "</td>");
tr.append("<td>" + details.signals[j].offset + "</td>");
tr.append("<td>" + details.signals[j].is_big_endian + "</td>");
tr.append("<td>" + details.signals[j].is_signed + "</td>");
tr.append("<td>" + details.signals[j].name + "</td>");
$('#table_1').append(tr);
}
}
});
});
This code is a bit unwieldy. I would suggest factoring out a function to create the rows. This way it's clear when they need to be created and you don't have to keep repeating details.signals[j]:
function tableRowForSignal(signal) {
return $('<tr />')
.append($("<td>").text(signal.start_bit));
.append($("<td>").text(signal.comment));
.append($("<td>").text(signal.bit_length));
.append($("<td>").text(signal.factor));
.append($("<td>").text(signal.offset));
.append($("<td>").text(signal.is_big_endian));
.append($("<td>").text(signal.is_signed));
.append($("<td>").text(signal.name));
}
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
var tr;
for (var i = 0; i < json.messages.length; i++) {
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
$('#table_1').append(tableRowForSignal(details.signals[j]));
}
}
});
});
You need to create a new row for each row
tr = $('<tr/>');
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
tr.append("<td>" + details.signals[j].start_bit + "</td>");
The first of these lines needs to be inside the loop where you create the cells that go inside it.
$(document).ready(function() {
$.getJSON("CAN_gen_1.json", function(json) {
for (var i = 0; i < json.messages.length; i++) {
var details = json.messages[i];
for (var j = 0; j <= details.signals.length; j++) {
var tr = $('<tr>');
tr.append("<td>" + details.signals[j].start_bit + "</td>");
tr.append("<td>" + details.signals[j].comment + "</td>");
tr.append("<td>" + details.signals[j].bit_length + "</td>");
tr.append("<td>" + details.signals[j].factor + "</td>");
tr.append("<td>" + details.signals[j].offset + "</td>");
tr.append("<td>" + details.signals[j].is_big_endian + "</td>");
tr.append("<td>" + details.signals[j].is_signed + "</td>");
tr.append("<td>" + details.signals[j].name + "</td>");
tr.append("</tr>");
$('#table_1').append(tr);
}
}
});
});
You have to open the row before the for with
<tr>
and after all the appends you should close it with
</tr>
Related
I have two JavaScript functions, one to generate a table and the other to delete a row by removing the node from the Firebase database. I keep getting an error that says deleteRecord() function is undefined. Please assist...
function generate_table(){
$('#emp_body').html('');
console.log(dArr);
for (var i = 0; i < dArr.length; i++) {
var tr;
tr = $('<tr/>');
var strSleeve = "View Sleeve";
var sleeveLink = strSleeve.link(dArr[i][1].downloadURLSleeve);
var strAud = "View Audio";
var audioLink = strAud.link(dArr[i][1].downloadURLFile);
tr.append("<td>" + (i+1) + "</td>");
tr.append("<td>" + childKeys[i] + "</td>");
tr.append("<td>" + dArr[i][1].stageName + "</td>");
tr.append("<td>" + dArr[i][1].fullName + "</td>");
tr.append("<td>" + dArr[i][1].email + "</td>");
tr.append("<td>" + dArr[i][1].city + "</td>");
tr.append("<td>" + dArr[i][1].cell + "</td>");
tr.append("<td>" + sleeveLink + "</td>");
tr.append("<td>" + audioLink + "</td>");
tr.append('<td>' + '<button id="deleteBtn" onclick="deleteRecord(\''+childKeys[i]+'\');" class="btn btn-danger">Delete Record</button>' + '</td>');
$('#emp_body').append(tr);
}
}
// DELETE FUNCTION
function deleteRecord(key){
var refDB = firebase.database().ref().child('submissions/'+key);
refDB.once("value")
.then(function(snapshot) {
snapshot.ref.remove();
alert("Record deleted..!");
}).catch(function(error) {alert("Data could not be deleted." + error);});
}
You should do as follows:
function deleteRecord(key){
var refDB = firebase.database().ref('submissions/' + key);
refDB.remove()
.then(function() {
console.log("Remove succeeded.")
})
.catch(function(error) {
console.log("Remove failed: " + error.message)
});
}
See the corresponding doc here: https://firebase.google.com/docs/reference/js/firebase.database.Reference#remove
You should not use the once() method which is used to read data, as explained here: https://firebase.google.com/docs/reference/js/firebase.database.Reference#once
I figured out a workaround. I think things will get easier from here. For now I am going to use the url to the specific node and delete the item from firebase while I try to figure out a better approach.
function generate_table(){
$('#emp_body').html('');
console.log(dArr);
for (var i = 0; i < dArr.length; i++) {
var tr;
tr = $('<tr/>');
var strSleeve = "View Sleeve";
var sleeveLink = strSleeve.link(dArr[i][1].downloadURLSleeve);
var strAud = "View Audio";
var audioLink = strAud.link(dArr[i][1].downloadURLFile);
tr.append("<td>" + (i+1) + "</td>");
tr.append("<td>" + childKeys[i] + "</td>");
tr.append("<td>" + dArr[i][1].stageName + "</td>");
tr.append("<td>" + dArr[i][1].fullName + "</td>");
tr.append("<td>" + dArr[i][1].email + "</td>");
tr.append("<td>" + dArr[i][1].city + "</td>");
tr.append("<td>" + dArr[i][1].cell + "</td>");
tr.append("<td>" + sleeveLink + "</td>");
tr.append("<td>" + audioLink + "</td>");
var deleteLink = 'https://myFirebaseAuthDomain.firebaseio.com/submissions'+'/'+ childKeys[i];
tr.append('<td>' + '<button id="deleteBtn" class="btn btn-danger">Delete Record</button>' + '</td>');
$('#emp_body').append(tr);
document.getElementById("deleteBtn").onclick = function()
{
console.log("AHOY!" + deleteLink);
var win = window.open(deleteLink, '_blank');
win.focus();
};
}
}
Typically, you fetch the data for the table and at that point Firebase is out of the picture. You take the response data and use JavaScript or whateverScript to build out your UI as you like, in your case you want a table.
I recommend that you add a dataset property to each table row which hold the value of whatever node that row represents, e.g. dataset.myid = a8hKE21Nswtevr applied to each <tr>.
You then appy a click listener to the entire table, or to the rows (by class), and all you have to do is evt.target.parentElement.dataset.myid to get the specific thing the end user clicked.
You then take that uid and talk to firebase as needed.
I have a dynamic table which is being created with jquery. The problem I face is, jquery interferes my string so it's not being parsed correctly to onclick method.
for (var i = 0; i < data.result.list.length; i++)
{
var tr = $("<tr></tr>");
tr.append("<td>" + "<a onclick='" + data.result.list[i].cfunction + "'>" + data.result.list[i].cvalue + "</a>" + "</td>");
tr.append("<td>" + + "</td>");
table.append(tr);
}
data.result.list[i].cfunction has a string value like "getMyMethod('My parameter')" which is basically calling a method with parameter in quotes.
But after jQuery parses this to onclick function it's value changes as onclick="getMyMethod(" my="" parameter')'=""
here is the generated html:
<a onclick="getMyMethod(" my="" parameter')'="" >My Value</a>
Can anyone put me in the right direction?
Change this line
"<a onclick='" + data.result.list[i].cfunction + "'>"
to this
'<a onclick="' + data.result.list[i].cfunction + '">'
You internal double quotes " needs to be escaped
var func = data.result.list[i].cfunction.replace( /"/g, "\\\"" );
tr.append("<td>" + "<a onclick='" + func + "'>" + data.result.list[i].cvalue + "</a>" + "</td>");
you should modify code with:
tr.append(
$("<td></<td>").append(
$("<a></a>")
.attr({
"href" : "#"
})
.text(data.result.list[i].cvalue)
.attr({
"onclick" : data.result.list[i].cfunction
})
)
);
You can modify your cfunction items in the data like this (encode):
cfunction: "getMyMethod(\"My parameter\")",
This worked in the console (make sure the table ID exists):
var data = {
result: {
list: [
{
cfunction: "getMyMethod(\"My parameter 1\")",
cvalue: "1"
},
{
cfunction: "getMyMethod(\"My parameter 2\")",
cvalue: "2"
}
]
}
}
var table = $("#testTable");
for (var i = 0; i < data.result.list.length; i++) {
var tr = $("<tr></tr>");
tr.append("<td>" + "<a onclick='" + data.result.list[i].cfunction + "'>" + data.result.list[i].cvalue + "</a>" + "</td>");
tr.append("<td>" + + "</td>");
table.append(tr);
}
var getMyMethod = function (funcParam) {
console.log(funcParam);
};
Can you try this. And be sure your data.result.list[i].cfunction value is
"getMyMethod('My parameter')"
for (var i = 0; i < data.result.list.length; i++)
{
var tr = $("<tr></tr>");
tr.append("<td>" + "<a onclick=\" " + data.result.list[i].cfunction +
"\" >" + data.result.list[i].cvalue + "</a>" + "</td>");
tr.append("<td>" + + "</td>");
table.append(tr);
}
I have this Table where I need to merge cells with same value for a column Week.
Below is the Table I am getting as an output right now:
Week Project OS TotalTests #cycle of run
1 P1 ABC 0 0
1 P2 XYZ 4799 1
I want the output to be like ( 1 should be placed at the center of a cell) :
Week Project OS TotalTests #cycle of run
1 P1 ABC 0 0
P2 XYZ 4799 1
Here is the code:
function BindTable(startWW, endWW, selPhaseNumber, selctedYear) {
var url = webApiUrl + .....
$('#GraphTable > tbody > tr ').remove();
$.ajax({
url:url,
type: "Get",
dataType: "json",
data: { .... },
crossDomain: true,
success: function (data) {
if (data.length > 0) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].WW + "</td>");
tr.append("<td>" + data[i].Project + "</td>");
tr.append("<td>" + data[i].OS + "</td>");
tr.append("<td>" + data[i].TotalTests + "</td>");
tr.append("<td>" + data[i].CycleRun + "</td>");
$('#GraphTable').append(tr);
}
}
else {
tr = $('<tr/>');
tr.append("<th colspan='10' style='text-align:center'>No Data to display</th>");
$('#GraphTable').append(tr);
}
}
});
}
Any help ?
You can combine cells with the rowspan attribute. The Problem: If you loop through the data from the beginning, you don't know the right value for the rowspan-attribute, because ithas to be placed in the first td-element!
Solution: Loop through it from the end to the beginning:
function success(data) {
if (data.length > 0) {
var oldValue = data[data.length-1].WW,
c=1;
for (var i = data.length-1; i >= 0; i--) {
let $tr = $('<tr/>');
if(i==0 || oldValue != data[i-1].WW) {
$tr.append("<td rowspan=\""+c+"\">" + data[i].WW + "</td>");
c = 1;
if(i>0) oldValue = data[i-1].WW;
} else {
c++;
}
$tr.append("<td>" + data[i].Project + "</td>");
$tr.append("<td>" + data[i].OS + "</td>");
$tr.append("<td>" + data[i].TotalTests + "</td>");
$tr.append("<td>" + data[i].CycleRun + "</td>");
$('#GraphTable').prepend($tr);
}
} else {
let $tr = $('<tr/>');
$tr.append("<th colspan='5' style='text-align:center'>No Data to display</th>");
$('#GraphTable').append($tr);
}
}
working fiddle
EDIT: working fiddle with head-line
changed the loop order and naming convention.
If you track the last DataWW you could print it or not. You only need to print when last DataWW is different from current DataWW. You can adjust your for loop like this:
var tr;
var lastDataWW = null
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
if (lastDataWW != data[i].WW) {
tr.append("<td>" + data[i].WW + "</td>");
else {
tr.append("<td> </td>");
}
tr.append("<td>" + data[i].Project + "</td>");
tr.append("<td>" + data[i].OS + "</td>");
tr.append("<td>" + data[i].TotalTests + "</td>");
tr.append("<td>" + data[i].CycleRun + "</td>");
$('#GraphTable').append(tr);
lastDataWW = data[i].WW
}
And as Santi said below the comments, you could center the first column if you add this css in your style sheet.
/* CSS */
#GraphTable tr td:first-child {
text-align: center;
}
I'm trying to parse a JSON object into an html table however I can't seem to get it right.
DESIRED FORMAT:
Last Year This Year Future Years
45423 36721 873409
CURRENT FORMAT:
Last Year 45423
This Year 36721
Future Years 873409
JSON:
[{column_name:"Last Year", "column_data":45423},{column_name:"This Year", "column_data":36721},{column_name:"Future Years", "column_data":873409}]
HTML:
<div class="panel-body">
<div id="main-aged-debtors-bar" style="height: 250px"></div>
<div>
<table class="table table-hover" id="crpw_table">
<thead>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
CODE:
$.getJSON(url, jsonObject,
function (data) {
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].column_name + "</td>");
tr.append("<td>" + data[i].column_data + "</td>");
$('#crpw_table').append(tr);
}
});
It's not much different
$.getJSON(url, jsonObject,
function (data) {
tr1 = $('<tr/>');
tr2 = $('<tr/>');
for (var i = 0; i < data.length; i++) {
tr1.append("<td>" + data[i].column_name + "</td>");
tr2.append("<td>" + data[i].column_data + "</td>");
}
$('#crpw_table').append(tr1);
$('#crpw_table').append(tr2);
}
);
$.getJSON(url, jsonObject,
function (data) {
var tr = $('<tr/>');
for (var i = 0; i < data.length; i++) {
tr.append("<td>" + data[i].column_name + "</td>");
}
$('#crpw_table').append(tr);
tr = $('<tr/>');
for (i = 0; i < data.length; i++) {
tr.append("<td>" + data[i].column_data + "</td>");
}
$('#crpw_table').append(tr);
});
Try,
$.getJSON(url, jsonObject,
function (data) {
var tr1 = $('<tr/>');
var tr2 = $('<tr/>');
for (var i = 0; i < data.length; i++) {
tr1.append("<td>" + data[i].column_name + "</td>");
tr2.append("<td>" + data[i].column_data + "</td>");
}
$('#crpw_table').append(tr1).append(tr2);
});
I have an ajax function which select data from database base on entered information i want this information in a table having a format like this
System Id | Last Name | First Name | Middle Name | Address
Here is my ajax
$.ajax({
type: 'POST',
url: '../include/OwnerInformation.php',
dataType: "json",
data: {
lastname: last_name,
firstname: first_name,
sysid: sys_id,
address: address
},
success: function(data) {
console.log(data);
var tr = ("#searchresults");
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + "<a id=" + data[i].sys_id + " href='#' value='" + data[i].sys_id + "'>" + data[i].sys_id + "</a>" + "</td>");
tr.append("<td>" + data[i].firstname + "</td>");
tr.append("<td>" + data[i].middlename + "</td>");
tr.append("<td>" + data[i].lastname + "</td>");
tr.append("<td>" + data[i].address + "," + "</td>");
$('table').append(tr);
}
}
});
I got the tutorial for adding row here but it is not behaving like i want it to.What i want is
Result will show in a specific table (search result table) - ok
The table will have a fix number of row (10 rows)
If the result is below 10 the row will still be 10 if row is more
than 10 it will show the next 10 with next and previous button
For your number 2:
Just use
for (var i = 0; i < 10; i++)
Then if data[i] is null, you could instantiate empty values for data[i]
For your number 3:
You should edit your php so it accept something like table.php?limit=10&startRow=10 (this should fetch the second page)
first of all: The first ("#searchresults") line you forgot to add the dollar sign $. So $("#searchresults").
Secondly: You shouldn't reassign the variable for this kind of task
Finally. My solution:
var table = $("#searchresults");
for (var i = 0; i < 10; i++) {
if(data[i]==null)
data[i] = {};
var tr = $('<tr/>');
tr.append("<td>" + "<a id=" + data[i].sys_id + " href='#' value='" + data[i].sys_id + "'>" + data[i].sys_id + "</a>" + "</td>");
tr.append("<td>" + data[i].firstname + "</td>");
tr.append("<td>" + data[i].middlename + "</td>");
tr.append("<td>" + data[i].lastname + "</td>");
tr.append("<td>" + data[i].address + "," + "</td>");
table.append(tr);
}
i know it's not pretty and maybe cause some problems down the road. But hey!
var data = [
{
firstname:"Heinrich",
middlename:"Lelouch",
lastname:"Breinholdt",
address:"German smurtz"
},
{
firstname:"Cate",
middlename:"Brom",
lastname:"Lriah",
address:"Somewhere"
},
{
firstname:"Funky",
middlename:"Daddy",
lastname:"Man",
address:"Funky land"
}
];
///// You don't even need to touch this code!!!
var table = $("#searchresults");
(function(){// generate header row
var tr = $('<tr>');
if(data && data.length)
for(var key in data[0])
tr.append("<td class='table-header'>"+key+"</td>");
table.append(tr);
})();
// generate content rows
for (var i = 0; i < 10; i++) {
var tr = $('<tr>');
if(data[i])
for(var key in data[i])
tr.append("<td>" + data[i][key] + "</td>");
else
for(var key in data[0])
tr.append("<td> </td>");
table.append(tr);
}
#searchresults{
border-collapse: collapse;
}
#searchresults td{
border: 1px solid grey;
}
#searchresults .table-header{
border-bottom: 2px solid black;
padding: 3px 5px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="searchresults"></table>