HTML table formatting issue - parsing jSON object into an HTML table - javascript

I have some code that grabs a JSON objects and displays it in a HTML table, however the table is not displaying correctly.
I want the table to be displayed like this:
_________________
| Product1 |
==================
| 1852ak | 2016 |
==================
| refurbished |
__________________
Here is my code:
var product = {
"name": "Product1",
"model": "1852ak",
"year": "2016",
"details": "refurbished"
}
$(document).ready(function() {
var row = $('<tr>');
row.append('<tr><td colspan = 2s>' + product.name + '</td></tr>');
row.append('<tr><td>' + product.model + '</td></tr>');
row.append('<td>' + product.year + '</td></tr>');
row.append('<tr><td>' + product.details + '</td></tr>');
$('#sample').append(row);
});
Any help would be greatly appreciated!

The problem is that you're adding rows to your existing rows.
In addition to this, you are considering the table to be one singular 'object', and are adding both the rows and the cells directly to the table. The table cells should be added to their containing rows.
What I would recommend doing is defining three separate rows as independent variables, then adding the cells to their respective rows. As the row has all of its content created, it gets added to the table:
var product = {
"name": "Product1",
"model": "1852ak",
"year": "2016",
"details": "refurbished"
}
$(document).ready(function() {
var table = $('#sample');
var row1 = $('<tr>');
var row2 = $('<tr>');
var row3 = $('<tr>');
row1.append('<td colspan = 2>' + product.name + '</td>');
table.append(row1);
row2.append('<td>' + product.model + '</td>');
row2.append('<td>' + product.year + '</td>');
table.append(row2);
row3.append('<td colspan = 2>' + product.details + '</td>');
table.append(row3);
});
td {
border: 1px solid black;
text-align: center;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sample"></table>
Hope this helps! :)

Try this Code:
var product =
{
"name":"Product1",
"model":"1852ak",
"year":"2016",
"details":"refurbished"
}
$(document).ready(function()
{
var row =$('table');
row.append ('<tr><td colspan = "2">' + product.name + '</td></tr>');
row.append('<tr><td>' + product.model + '</td><td>' + product.year + '</td></tr>');
row.append ('<tr><td colspan = "2">' + product.details + '</td></tr></table>');
$('#sample').append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample"></div>
Presuming that $("#sample") is your table

Related

build unique table with JQuery AJAX

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

Table Not Populating as I expected using Jquery

I am trying to populate a table using a JSON file. When I run this through the browser, my first row populates. However the other rows do not. Can someone please point out to me what I am doing wrong? Am I not looping this correctly? Thank you in advance.
$(document).ready(function() {
$.getJSON( "data.json", function(data) {
var htmlToRender= [];
var item;
for (var i = 0; i < data.length; i++) {
item = data[i];
console.log(data[i]);
htmlToRender = '<tr><td>' + item.name + '</td>'
'<td>' + item.description + '</td>'
console.log(item.description)
'<td>Open In Google Mapspwd</td></tr>';
console.log(item.location);
$('#hot-spots').append(htmlToRender);
console.log(htmlToRender);
};
});
});
The lines following htmlToRender = '<tr><td>' + item.name + '</td>' look a bit suspicious--you're missing a + sign to concatenate these additional strings, and sprinkled console.logs amidst the string build isn't helping the cause.
I recommend using a string template:
const item = {
name: "hello",
description: "world",
location: "somewhere"
};
const htmlToRender = `
<tr>
<td>${item.name}</td>
<td>${item.description}</td>
<td>
Open In Google Maps
</td>
</tr>
`;
$('#hot-spots').append(htmlToRender);
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="hot-spots"></table>

Node js not recognizing input fields that were added dynamically to the form

I saw a similar question but did not know how to apply it to node js. I created a cart, a user clicks to add an item and that item is added to the form using jquery. On submit however, the only form field acknowledge is the totalCost which was not dynamically added.
My pug file (the relevant portion):
h1#spendable 50000
table
form#cartitems(method='POST' action='/store')
tbody
tr#buyit(style='border-bottom:0px solid white; height:50px; display:none;')
td#purchCost <b> Total: </b>
input#costcost.minIn.nolineinput(name='totalCost' type='text' readonly)
tr
td(colspan=2)
button(type='submit' style='width:100%; padding:5px 0px;') Buy
My javascript file looks like this:
function addToCart(butt){
var $spendable = $('#spendable');
var balance = Number( $spendable.text() );
var itmCost = Number($(butt).prev().prev().text());
var boughtItems = $('.firstline').length;
if(balance > itmCost && boughtItems < 4){
var imgSrc = $(butt).parent().prev().attr('src');
var specific = $(butt).prev().val();
var specificL= $(butt).prev().text();
var itmName = $(butt).prev().prev().prev().text();
var itmType = $(butt).parent().parent().parent().prop('id');
var purchCost= Number( $('#purchCost .minIn').val() );
//create a demo
if (itmType == 'Treat' || itmType == 'Prize'){
alert(itmType);
$('#cartcontainer table tbody').prepend("<tr class='firstline'><td class='smtd' rowspan=2 ><img class='demo' src='" + imgSrc + "'></img></td><td><input type='text' class='nolineinput' name='itmName' value='" + specific +"|" + itmName + "' readonly></input></td><tr><td><div class='minidiv'><p>" + Number(itmCost) + "</p></div><div class='microdiv'><input id='chck' type = 'checkbox' name = 'itmKind' onclick='remove(this)' checked></input></div></td></tr>")
if(boughtItems ==0){
$('#buyit').show()
}
}else{
$('#cartcontainer table tbody').prepend("<tr class='firstline'><td class='smtd' rowspan=2 ><img class='demo' src='" + imgSrc + "'></img></td><td><input type='text' class='nolineinput' name='itmName' value='" + itmName +"| " + specificL + "' readonly></input></td><tr><td><div class='minidiv'><p>" + Number(itmCost) + "</p></div><div class='microdiv'><input class='chck' type = 'checkbox' name = 'itmKind' value='" + itmCost + "' onclick='remove(this)' checked></input></div></td></tr>");
if(boughtItems ==0){
$('#buyit').show()
}
}
var total= purchCost + itmCost;
$('#purchCost .minIn').val(total);
$spendable.text( balance-itmCost);
}else if (boughtItems >= 4){
alert("You've reached the max amount of item\n you can purchase. Buy more next week!")
}else {
alert('Sorry you do not have enough\n points to purchase this item.')
}
}
Also I should mention I'm using body-parser and when i console.log( req.body) the only thing i get back is {totalCost:'1500'} but what I wish to see is: {itmName:'Caprisun', itmKind:'Cherry', totalCost:'1500'}
Nevermind solved it on my own. The table should have been created inside the form. Table, tbody , tr, td should've all been together like so:
form
table
tbody
tr
td Total
td
input(type='text' name='itemName')

datatable append html but got refreshed?

Not sure what is wrong, for me my code has the right logic. But somehow the html didn't stay after 2nd click onward. I expect my custom html would appear after the newly added tr.
my function
function appendRow(name, position, office, age, date,salary) {
var t = $('#example').DataTable();
var node = t.row.add([
name,
position,
office,
age,
date,
salary,
]).draw().node();
var detail_row = '';
detail_row = '<h3>Custom HTML</h3>';
$(node).addClass('result-row');
node = node.outerHTML += detail_row;
$(node).hide().fadeIn('normal');
}
https://jsfiddle.net/282w8yfk/
it is happening in this way because you applied sorting on the name column, so datatable being quite smart it adds the row where it needs to be... so if you want to add that in the last remove sorting option on name column...
and here is a small code change:
$(document).ready(function() {
/* Formatting function for row details - modify as you need */
function format(d) {
console.log(d);
// `d` is the original data object for the row
return '<table cellpadding="4" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Name:</td>' +
'<td>' + d[0] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Full Name:</td>' +
'<td>' + d[4] + '</td>' +
'</tr>' +
'<tr>' +
'<td>Extra info:</td>' +
'<td>And any further details here (images etc)...</td>' +
'</tr>' +
'</table>';
}
var table = $('#example').DataTable({
"columnDefs": [{
"targets": [4],
"visible": false,
"searchable": false
}]
/* the problem is here, it won't work if I enable sorting*/
});
function appendRow() {
var t = $('#example').DataTable();
var node = t.row.add([
"James Bond",
"Spy", "55", "$9000", "James Bond Larry"
]).draw().node();
console.log(node);
$(node).addClass('result-row').hide().fadeIn('normal');
};
$('#add').click(function() {
appendRow();
});
$('#example tbody').on('click', '.result-row', function() {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
});
reference 1 - sort
reference 2 - row.add

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Categories

Resources