Format result after looping object - javascript

I'm looping an object and expect the result as elements of a table
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
},
pp_ = '<table><tbody>';
for (var i in db) {
if (db.hasOwnProperty(i)) {
var js = db[i].split(',');
for (var x in js) {
if (i.startsWith('pp_')) {
pp_ += '<tr><td>' + i + ' ' + x + ' : ' + js[x] + '</td></tr>';
}
}
}
}
pp_ += '</tbody></table>';
document.write(pp_);
I am splitting values that have commas so that each index of an array sits on 1 row (tr)
what I can't figure out is how to place elements with the same index on the same level (row) so I can I have something like
table, td {
border: 1px solid black;
}
<table>
<tbody>
<tr>
<td> pp_flavour 0 - its value </td>
<td> pp_fruit_batch 0 - its value </td>
</tr>
<tr>
<td> pp_flavour 1 - its value </td>
<td> pp_fruit_batch 1 - its value </td>
</tr>
<tr>
<td> pp_flavour 2 - its value </td>
<td> pp_fruit_batch 2 - its value </td>
</tr>
</tbody>
</table>
<br>
<table>
<tbody>
<tr>
<td> sl_favour 0 - its value </td>
<td> sl_appearance 0 - its value </td>
</tr>
<tr>
<td> sl_favour 1 - its value </td>
<td> sl_appearance 1 - its value </td>
</tr>
</tbody>
</table>
and so on...

You could try indexing the database like this:
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
};
var prefixes = ["pp", "ht", "sl"];
var prefixedDb = {};
var result = "";
for (var i in db) {
if (db.hasOwnProperty(i)) {
var parts = i.split("_");
var prefix = parts[0];
if (prefixes.indexOf(prefix) === -1) continue;
if (prefixedDb[prefix] === undefined) {
prefixedDb[prefix] = {};
}
prefixedDb[prefix][parts.slice(1).join("_")] = db[i];
}
}
for (var k in prefixedDb) {
if (prefixedDb.hasOwnProperty(k)) {
var db = prefixedDb[k];
var dbIndexed = {};
for (var i in db) {
if (db.hasOwnProperty(i)) {
var vals = db[i].split(',');
vals.forEach(function(val, j) {
if (dbIndexed[j] === undefined) {
dbIndexed[j] = {};
}
dbIndexed[j][i] = val;
});
}
}
result += "<table><tbody>";
for (var i in dbIndexed) {
if (dbIndexed.hasOwnProperty(i)) {
result += "<tr>";
var indexVals = dbIndexed[i];
for (var j in indexVals) {
if (indexVals.hasOwnProperty(j)) {
result += "<td>" + j + " " + i + " - " + indexVals[j] + "</td>";
}
}
result += "</tr>";
}
}
result += "</tbody></table>";
}
}
document.write(result);
table, td {
border: 1px solid black;
}
Please note that this code may not be the most optimized code for this task.

You can try adding each value of the table to a 2-D array and than form the table from this 2-D array
try below solution
NOTE: this will also work with different number of rows and Column.
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
};
function createTable(myKey){
var rows = [];
for (var dbKey in db) {
if (db.hasOwnProperty(dbKey)) {
if (dbKey.startsWith(myKey)) {
var values = db[dbKey].split(',');
for (var val in values) {
if (!rows[val])
rows[val] = [];
rows[val].push('<td>' + dbKey + ' ' + val + ' : ' + values[val] + '</td>');
}
}
}
}
var myTable = '<table><tbody>';
for (var i = 0; i < rows.length; i++) {
myTable += "<tr>" + rows[i].join("") + "</tr>";
}
myTable += '</tbody></table>';
return myTable;
}
var ht_table = createTable("ht_");
document.getElementById("myTable").innerHTML +="<br/>"+ ht_table;
var pp_table = createTable("pp_");
document.getElementById("myTable").innerHTML +="<br/>"+ pp_table;
var sl_table = createTable("sl_");
document.getElementById("myTable").innerHTML += "<br/>"+ sl_table;
table, td {
border-style: solid;
}
<p id="myTable">
</p>

You could take the wanted values out of the object, split them and take the max length for iterating the rows for the table. Then assemble the table by iterating the values.
var db = { pp_flavour: "ytv,yurtcrc,urt", pp_fruit_batch: "cuyt,cytc,yt,42" },
values = Object.keys(db).filter(k => k.startsWith('pp_')).map(k => (db[k] || '').split(',')),
length = values.reduce((r, a) => Math.max(r, a.length), 0),
table = document.createElement('table'),
tr,
i;
for (i = 0; i < length; i++) {
tr = document.createElement('tr');
table.appendChild(tr);
values.forEach(function (a) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(i in a ? a[i] : ''));
tr.appendChild(td);
});
}
document.body.appendChild(table);

Create a loop, incrementing a counter, which will determine if a key's split value should be output.
If there are no more values found at the index of the counter, stop looping.
var db = {
"id": "8",
"user_id": "24",
"batchno": "367727",
"ht_number": "jibhbu",
"ht_taste": "uvyutvc",
"pp_flavour": "ytv,yurtcrc,urt",
"pp_fruit_batch": "cuyt,cytc,yt",
"sl_flavour": "ouihyuigytvytc",
"sl_appearance": "rtctr"
},
s = '';
['pp_', 'ht_', 'sl_'].forEach(function(type) {
var i,
found = true;
s += '<table>';
for(i = 0 ; found ; i++) {
s += '<tr>';
found = false;
Object.keys(db).forEach(function(key) {
var js = db[key].split(',');
if(js[i] && key.startsWith(type)) {
found = true;
s += '<td>' + key + ' ' + i + ' : ' + js[i] + '</td>';
}
});
s += '</tr>';
}
s += '</table>';
});
document.write(s);
td {
border-bottom: 1px solid #bbb;
border-right: 1px solid #ddd;
padding: 0.5em;
}
table {
border: 1px solid black;
margin-bottom: 1em;
border-spacing: 0;
}

Related

I have a mysterious <BR> being added to my table

I cant figure out why a double <BR> is automatically being added to my newly appended table rows.
All you have to do is hit the enter key to cause the problem.
I don't want any <br> to be added, it screws up my data entry process.
The problem appears to be happening in the appenNewRow() function.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Text Area Order Input</title>
<style>
.myInputClass {
width: 120px;
}
.myOutputClass {
width: 240px;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
storeflag = true;
attribstart = "";
attribend = "";
output_result = "";
var row = 0;
var storeIndex = 0;
var productIndex = 0;
var thisstore_id=0;
function appendNewRow(inputType)
{
row++;
var markup = "<tr id='"+row+"'><td input-row='"+row+"' input-type='"+inputType+"' class='myInputClass' height='auto' contenteditable='true' placeholder='Next'></td><td output-row='"+row+"' class='myOutputClass'></td><td extra-row='"+row+"' class='extra'></td></tr>";
$("table tbody").append(markup);
myjunk = document.querySelector('[input-row="' + row + '"]').innerHTML;
document.querySelector('[input-row="' + row + '"]').innerHTML = "zzz";
document.getElementById(row).getElementsByClassName('myInputClass')[0].focus();
}
function getStore(thisstore)
{
}
function getProduct(thisstore_id, thisproduct_nickname)
{
}
$(document).ready(function(){
document.getElementById('1').getElementsByClassName('myInputClass')[0].focus();
lastKey = 13;
$("tbody").on('keypress', ".myInputClass", (function(event){
if (event.which == 13) { // Enter Key.
attribstart = "";
attribend = "";
row = Number($(this).attr('input-row'));
thishtml = $(this).html();
if ($(this).text().length > 0) {
x = $(this).text();
if (storeflag == true) {
thisstore_id = getStore(x);
} else {
getProduct(thisstore_id,x);
}
} else {
$(this).text("---");
appendNewRow('store');
storeflag = true;
//$('#YourContainer').find('br').remove();
$('[input-row="' + row + '"]').find('br').remove(); // Fixes an ajax bug.
}
} else {
} //end if
lastKey = event.which;
}));
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Input</th>
<th>Output</th>
<th>Extra</th>
</tr>
</thead>
<tbody>
<tr id='1'>
<td input-row='1' input-type='store' class='myInputClass' height='auto' contenteditable='true' placeholder='Just Start Typing a storename'></td>
<td output-row='1' class='myOutputClass'></td>
<td extra-row='1' class='extra'></td>
</tr>
</tbody>
</table>
</body>
</html>
I cleaned up the code you presented. It's a better practice to use all jQuery or all JavaScript. Based on the following testing, you may need to add the content and then make it Editable.
$(function() {
$("#empty").click(function() {
$("<tr>").appendTo($("table tbody"));
$("<td>").appendTo($("table tr:last")).prop("contenteditable", true);
});
$("#full").click(function() {
$("<tr>").appendTo($("table tbody"));
$("<td>").appendTo($("table tr:last")).html("Edit").prop("contenteditable", true);
});
});
table {
border: 1px solid black;
border-collapse: collapse;
padding: 0;
margin: 0;
}
table tr {
height: 1.5em;
}
table tr td {
border: 1px dashed black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>Non-Edit</td>
</tr>
</tbody>
</table>
<button id="empty">Add Empty Row</button>
<button id="full">Add Full Row</button>
We apply this to your code.
$(function() {
var storeflag = true,
attribstart = "",
attribend = "",
output_result = "",
row = 0,
storeIndex = 0,
productIndex = 0,
thisstore_id = 0;
function appendNewRow(inputType) {
var markRow = $("<tr>", {
id: ++row
}).appendTo($("table tbody"));
$("<td>", {
class: "myInputClass",
height: "auto",
placeholder: "Next",
"input-row": row,
"input-type": inputType
}).appendTo(markRow);
$("<td>", {
class: "myOutputClass",
"output-row": row
}).appendTo(markRow);
$("<td>", {
class: "extra",
"extra-row": row
}).appendTo(markRow);
$("td:eq(0)", markRow).html("Start").prop("contenteditable", true).focus();
}
function getStore(thisstore) {
$.ajax({
url: 'ajax_getstore',
data: "store=" + thisstore,
method: "GET",
dataType: "json",
cache: false,
success: function(data) {
var markup = "";
if (data.length > 1) {
$.each(data, function(thisname, thisvalue) {
var output = attribstart + thisvalue.fields.name + attribend;
markup += "<tr id='" + row + "'><td class='dyninput'>row:" + row + " - " + output + "</td></tr>";
});
} else {
$('[input-row="' + row + '"]').html(thisstore); // Fixes an ajax bug.
$('[output-row="' + row + '"]').attr('input-type', 'store');
$('[output-row="' + row + '"]').html(attribstart + data[0].fields.name + attribend);
}
thisstore_id = data[0].pk;
appendNewRow('product');
output_result = "";
}, // End success.
error: function() {
alert('error');
},
}); //End Ajax.
attribstart = "<b>";
attribend = "</b>";
storeflag = false; //reset storeflag.
}
function getProduct(thisstore_id, thisproduct_nickname) {
var qty = parseInt(thisproduct_nickname);
if (isNaN(qty)) {
qty = '1';
} else {
thisproduct_nickname = thisproduct_nickname.replace(qty, '');
}
$.ajax({
url: 'ajax_getproduct',
data: 'store_id=' + thisstore_id + '&qty=' + qty + '&product_nickname=' + thisproduct_nickname,
method: "GET",
dataType: "json",
cache: false,
success: function(data) {
var markup = "";
if (data.length > 1) {
$.each(data, function(thisname, thisvalue) {
var output = attribstart + thisvalue.fields.product_name + attribend;
markup = markup + "<tr id='" + row + "'><td class='dyninput'>row:" + row + " - " + output + "<br></td></tr>";
row++;
});
} else {
$('[input-row="' + row + '"]').html(thisproduct_nickname); // Fixes an ajax bug.
$('[output-row="' + row + '"]').attr('input-type', 'product');
$('[output-row="' + row + '"]').html(attribstart + qty + ' ' + data[0].fields.product_default_uom_code + ' ' + data[0].fields.product_name + attribend);
}
appendNewRow('product');
output_result = "";
}, // End success.
error: function() {
alert('error');
},
}); //End Ajax.
}
function display_result(data_output_result) {
var badjson = JSON.parse(data_output_result);
var myjson = badjson.replace("\\", "");
var goodjson = JSON.parse(myjson);
var markup = "";
$.each(goodjson, function(thisname, thisvalue) {
row = row + 1;
var output = attribstart + thisvalue.fields.name + attribend;
markup += "<tr id='" + row + "'><td class='dyninput'>row:" + row + " - " + output + "<br></td></tr>";
console.log(thisvalue.fields.id, thisvalue.fields.name);
});
$("table tbody#myOutputBodyId").append(markup);
output_result = "";
}
$('#1 .myInputClass').focus();
var lastKey = 13;
$("tbody").on('keypress', ".myInputClass", function(event) {
event.preventDefault();
if (event.which == 13) { // Enter Key.
attribstart = "";
attribend = "";
row = Number($(this).attr('input-row'));
thishtml = $(this).html();
if ($(this).text().length > 0) {
x = $(this).text();
if (storeflag == true) {
thisstore_id = getStore(x);
} else {
getProduct(thisstore_id, x);
}
} else {
$(this).text("---");
appendNewRow('store');
storeflag = true;
//$('#YourContainer').find('br').remove();
$('[input-row="' + row + '"]').find('br').remove(); // Fixes an ajax bug.
}
} //end if
lastKey = event.which;
});
});
.myInputClass {
width: 120px;
}
.myOutputClass {
width: 240px;
}
table,
td {
margin: 0px;
border-collapse: collapse;
padding: 0px;
border-spacing: 0px;
vertical-align: top;
}
table th {
border: 1px solid #6C220B;
border-spacing: 0px;
padding: 0px;
text-align: left;
}
table#myOutputTableId {
border: 0px;
padding: 0px;
margin: 0px;
align: top;
}
[xcontentEditable=true]:empty:before {
content: attr(placeholder);
opacity: 0.6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Input</th>
<th>Output</th>
<th>Extra</th>
</tr>
</thead>
<tbody>
<tr id='1'>
<td input-row='1' input-type='store' class='myInputClass' height='auto' contenteditable='true' placeholder='Just Start Typing a storename'></td>
<td output-row='1' class='myOutputClass'></td>
<td extra-row='1' class='extra'></td>
</tr>
</tbody>
</table>
The issue was the key capture from the Enter. This was injecting the new line in the editable and creating the <br>. We can use .preventDefault() to address this.
I am unable to test this code as it does not connect to any of the AJAX Urls.

How to add class by referring to array in html table

I would like to addclass in 2nd row, by referring to array and its index.
I prepared array and all that remains to add class by referring to index.
through my work, it didn't work well.
How can I achieve them?
Thanks
let html = ''
html += '<table>';
let i = 0;
html += '<tr>';
for (let d = 0; d < 15; d++) {
i = i + 1;
html += '<td data-layer=0>' + '<div>' + i + '</div>' + '</td>'
}
html += '</tr>';
for (let w = 0; w < 1; w++) {
html += '<tr>';
for (let d = 0; d < 15; d++) {
html += '<td class=color></td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
const arr = [1, 2, 10, 11, 14].map(String);
$("td .color")
.filter(function() { return $(this).index(arr); })
.addClass('red');
td {
transition-duration: 0.5s;
border: solid black 1px;
cursor: pointer;
}
div {
padding: 5px;
}
table {
border-collapse: collapse;
}
.color{
padding:5px;
}
.red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
You should not have any space between the tag name and the class if both refer the same element. You can use includes() to check if the index + 1 is exists in the array or not.
Try the following way:
let html = ''
html += '<table>';
let i = 0;
html += '<tr>';
for (let d = 0; d < 15; d++) {
i = i + 1;
html += '<td data-layer=0>' + '<div>' + i + '</div>' + '</td>'
}
html += '</tr>';
for (let w = 0; w < 1; w++) {
html += '<tr>';
for (let d = 0; d < 15; d++) {
html += '<td class=color></td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
const arr = [1, 2, 10, 11, 14];
$("td.color")
.filter(function() { return arr.includes($(this).index()+1); })
.addClass('red');
td {
transition-duration: 0.5s;
border: solid black 1px;
cursor: pointer;
}
div {
padding: 5px;
}
table {
border-collapse: collapse;
}
.color{
padding:5px;
}
.red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
You could tidy up your loops a bit by first building the indexes, and then use backquote to clean up your html template.
Note: you should be using double quotes for attributes eg class="color"
const columnCount = 15;
const columnIndexes = [...Array(columnCount).keys()]; // make array of indexes
const rowsCount = 1;
const rowIndexes = [...Array(rowsCount).keys()];
const html =
`<table>
<tr>
${columnIndexes.map(c =>
`<td data-layer="0"><div>${c + 1}</div></td>
`)}
</tr>
${rowIndexes.map(r =>
`<tr>
${columnIndexes.map(c =>
`<td class="${r % 2 === 0 ? 'red' : ''}"></td>`
)}
</tr>`
)}
</table>
`

Creating a dynamic table for dynamic data with a for loop html javascript

Im trying to add dynamic data generated in a for loop into a table with javascript. Heres my code
<script>
var setA = [];
var setB = [];
var newline = "<br>";
var space = " ";
for(var i = 1; i < 13; i++){
setA.push("<i+space);
}
document.write(setA+newline);
for(var i = 1; i < 13; i++){
setB.push(i*i+space);
}
document.write(setB);
</script>
this is the result:
1,2,3,4,5,6,7,8,9,10,11,12
1 ,4 ,9 ,16 ,25 ,36 ,49 ,64 ,81 ,100 ,121 ,144
the result im looking for is to have these numbers contained inside a table, ive looked at examples online but i dont know how i would apply it to this context
Are you familiar with the table HTML tag?
var code = "<table><tr>";
for (var i=0; i<13; i++) {
code += `<th>${i}</th>`;
}
code += "</tr><tr>";
for (var i=0; i<13; i++) {
code += `<th>${i*i}</th>`;
}
code += "</tr></table>";
document.write(code);
Please find below code snippet, it should solve your problem:
$(document).ready(function() {
this.json = {
"Students": [{
"id": "1",
"hometown": "London",
"gender": "Male",
"GPA": "8",
"name": "Lee",
},
{
"id": "2",
"hometown": "NY",
"gender": "Male",
"GPA": "9",
"name": "Shaldon",
}, {
"id": "3",
"hometown": "Paris",
"gender": "Female",
"GPA": "7",
"name": "Julie",
}
]
};
this.renderTable = function(Students) {
var tbody = document.getElementById('tbody');
tbody.innerHTML = "";
for (var i = 0; i < Students.length; i++) {
var tr = "<tr>";
tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
tr += "<hr>";
tbody.innerHTML += tr;
}
}
this.renderTable(this.json.Students);
console.log(this.json.Students);
//code for filtering//
this.Filter = function() {
var search = document.getElementById('search');
var category = document.getElementById('category');
var filteredObj = this.json.Students;
filteredObj = $.map(this.json.Students, function(val, key) {
if (search.value === val[category.value]) return val;
});
filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>
<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
<option value = "id">ID</option>
<option value = "hometown">HomeTown</option>
<option value = "gender">Gender</option>
<option value = "GPA">GPA</option>
<option value = "name">NAME</option>
</select>
<button onclick="Filter()">Filter</button>
<table>
<tbody id="tbody"></tbody>
</table>

Possible to only run code block inside for loop once?

I'm using the loop to find whole table columns containing cells with a certain class and it works fine for applying class and the other stuff below. The only problem is that I would also like to output the value of the cells once. Is this possible somehow?
$('td:first-child').each(function() {
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
var text = column.text().toUpperCase();
$("#textout").append(text + "!!");
}
}
});
Update:
$('td:first-child').each(function() {
for(var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
if (col == 5) {
$( ".bingocl" ).fadeIn(2000);
column.addClass("bingo", 2000);
column.each(function() {
$("#textout").append($(this).html() + " ");
});
break;
}
}
});
function in it's entirety:
var main = function() {
//Styling the rows
$(".tabell tbody").find("tr").each(function(idx) {
var row = $(this);
if (row.find("td").length == row.find("td.check").length) {
row.addClass("bingo");
$(".bingocl").fadeIn(2000);
var text = row.find("td").text().toUpperCase();
$("#textout").append(text + "!!");
}
});
//styling cols
$('td:first-child').each(function() {
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
var text = column.text().toUpperCase();
$("#textout").append(text + "!!");
break;
}
}
});
}
$(document).ready(main);
Provided you already have access to your winning row/column (you add a bingo class to them), you can access each individual element to output it's value.
Your code becomes:
var main = function() {
//Styling the rows
$(".tabell tbody").find("tr").each(function(idx) {
var row = $(this);
if (row.find("td").length == row.find("td.check").length) {
row.addClass("bingo");
$(".bingocl").fadeIn(2000);
// Iterate your row elements
row.each(function(){document.write($(this).html() + " ");});
}
});
//styling cols
//$('td:first-child').each(function() { <- remove this
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
// Iterate your column elements
column.each(function(){document.write($(this).html() + " ");});
break;
}
}
//}); <- remove this
}
$(document).ready(main);
Live example
var column = $(".selected_column");
var row = $(".selected_row");
column.addClass("bingo");
row.addClass("bingo");
column.each(function() {
$("#textout").append($(this).html() + " ");
});
row.each(function() {
$("#textout").append($(this).html() + " ");
});
.selected_column {
background: blue;
}
.selected_row {
background: yellow;
}
.selected_column.selected_row {
background: green;
}
.bingo {
border: 2px solid lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>A</td>
<td class="selected_column">B</td>
<td>C</td>
<td>D</td>
<td>E</td>
</tr>
<tr>
<td>F</td>
<td class="selected_column">G</td>
<td>H</td>
<td>I</td>
<td>J</td>
</tr>
<tr>
<td>K</td>
<td class="selected_column">L</td>
<td>M</td>
<td>N</td>
<td>O</td>
</tr>
<tr>
<td class="selected_row">P</td>
<td class="selected_column selected_row">Q</td>
<td class="selected_row">R</td>
<td class="selected_row">S</td>
<td class="selected_row">T</td>
</tr>
<tr>
<td>U</td>
<td class="selected_column">V</td>
<td>W</td>
<td>X</td>
<td>Y</td>
</tr>
</table>
<p id="textout">#textout : </p>
You can do column.html(); to get the cell content
You could always try with break.
Link: MDN
Try to use break:
$('td:first-child').each(function() {
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
var text = column.text().toUpperCase();
$("#textout").append(text + "!!");
break;
}
}
});

Create table using Javascript

I have a JavaScript function which creates a table with 3 rows 2 cells.
Could anybody tell me how I can create the table below using my function (I need to do this for my situation)?
Here is my javascript and html code given below:
function tableCreate() {
//body reference
var body = document.getElementsByTagName("body")[0];
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
for (var j = 0; j <= 2; j++) {
// table row creation
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row " + j + ", column " + i);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
body.appendChild(tbl);
// tbl border attribute to
tbl.setAttribute("border", "2");
}
<table width="100%" border="1">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td rowspan="2"> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
Slightly shorter code using insertRow and insertCell:
function tableCreate() {
const body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '1px solid black';
for (let i = 0; i < 3; i++) {
const tr = tbl.insertRow();
for (let j = 0; j < 2; j++) {
if (i === 2 && j === 1) {
break;
} else {
const td = tr.insertCell();
td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
td.style.border = '1px solid black';
if (i === 1 && j === 1) {
td.setAttribute('rowSpan', '2');
}
}
}
}
body.appendChild(tbl);
}
tableCreate();
Also, this doesn't use some "bad practices", such as setting a border attribute instead of using CSS, and it accesses the body through document.body instead of document.getElementsByTagName('body')[0];
This should work (from a few alterations to your code above).
function tableCreate() {
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.style.width = '100%';
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
for (var i = 0; i < 3; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
if (i == 2 && j == 1) {
break
} else {
var td = document.createElement('td');
td.appendChild(document.createTextNode('\u0020'))
i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null;
tr.appendChild(td)
}
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
}
tableCreate();
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
addTable();
<div id="myDynamicTable"></div>
Here is the latest method using the .map function in javascript.
You create a table in html and then insert body with javascript.
const data = [{Name:'Sydney', Day: 'Monday', Time: '10:00AM'},{Name:'New York', Day: 'Monday',Time: '11:00AM'},]; // any json data or array of objects
const tableData = data.map(value => {
return (
`<tr>
<td>${value.Name}</td>
<td>${value.Day}</td>
<td>${value.Time}</td>
</tr>`
);
}).join('');
const tableBody = document.querySelector("#tableBody");
tableBody.innerHTML = tableData;
<table border="2">
<thead class="thead-dark">
<tr>
<th scope="col">Tour</th>
<th scope="col">Day</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
<script>
var student;
for (var j = 0; j < 10; j++) {
student = {
name: "Name" + j,
rank: "Rank" + j,
stuclass: "Class" + j,
};
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = student.name,
cell2.innerHTML = student.rank,
cell3.innerHTML = student.stuclass;
}
</script>
</body>
</html>
This solution will be perfect when you want rows and columns dynamic. You can accept rows and columns as arguments.
function tableCreate(row, col){
let body = document.body;
let tbl = document.createElement('table');
tbl.style.width = '200px';
tbl.style.border = '1px solid black';
for(let i = 0; i < row; i++){
let tr = tbl.insertRow();
for(let j = 0; j < col; j++){
let td = tr.insertCell();
td.appendChild(document.createTextNode(`${i},${j}` ));
td.style.border = '1px solid black';
}
}
body.appendChild(tbl);
}
tableCreate(4,4);
Output -
<!DOCTYPE html>
<html>
<body>
<p id="p1">
<b>Enter the no of row and column to create table:</b>
<br/><br/>
<table>
<tr>
<th>No. of Row(s) </th>
<th>No. of Column(s)</th>
</tr>
<tr>
<td><input type="text" id="row" value="4" /> X</td>
<td><input type="text" id="col" value="7" />Y</td>
</tr>
</table>
<br/>
<button id="create" onclick="create()">create table</button>
</p>
<br/><br/>
<input type="button" value="Reload page" onclick="reloadPage()">
<script>
function create() {
var row = parseInt(document.getElementById("row").value);
var col = parseInt(document.getElementById("col").value);
var tablestart="<table id=myTable border=1>";
var tableend = "</table>";
var trstart = "<tr bgcolor=#ff9966>";
var trend = "</tr>";
var tdstart = "<td>";
var tdend = "</td>";
var data="data in cell";
var str1=tablestart + trstart + tdstart + data + tdend + trend + tableend;
document.write(tablestart);
for (var r=0;r<row;r++) {
document.write(trstart);
for(var c=0; c<col; c++) {
document.write(tdstart+"Row."+r+" Col."+c+tdend);
}
}
document.write(tableend);
document.write("<br/>");
var s="<button id="+"delete"+" onclick="+"deleteTable()"+">Delete top Row </button>";
document.write(s);
var relod="<button id="+"relod"+" onclick="+"reloadPage()"+">Reload Page </button>";
document.write(relod);
}
function deleteTable() {
var dr=0;
if(confirm("It will be deleted..!!")) {
document.getElementById("myTable").deleteRow(dr);
}
}
function reloadPage(){
location.reload();
}
</script>
</body>
</html>
Might not solve the problem described in this particular question, but might be useful to people looking to create tables out of array of objects:
function createTable(objectArray, fields, fieldTitles) {
let body = document.getElementsByTagName('body')[0];
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let thr = document.createElement('tr');
fieldTitles.forEach((fieldTitle) => {
let th = document.createElement('th');
th.appendChild(document.createTextNode(fieldTitle));
thr.appendChild(th);
});
thead.appendChild(thr);
tbl.appendChild(thead);
let tbdy = document.createElement('tbody');
let tr = document.createElement('tr');
objectArray.forEach((object) => {
let tr = document.createElement('tr');
fields.forEach((field) => {
var td = document.createElement('td');
td.appendChild(document.createTextNode(object[field]));
tr.appendChild(td);
});
tbdy.appendChild(tr);
});
tbl.appendChild(tbdy);
body.appendChild(tbl)
return tbl;
}
createTable([
{name: 'Banana', price: '3.04'},
{name: 'Orange', price: '2.56'},
{name: 'Apple', price: '1.45'}
],
['name', 'price'], ['Name', 'Price']);
I hope you find this helpful.
HTML :
<html>
<head>
<link rel = "stylesheet" href = "test.css">
<body>
</body>
<script src = "test.js"></script>
</head>
</html>
JAVASCRIPT :
var tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div');
for (row = 1; row < 101; row += 1) {
tableString += "<tr>";
for (col = 1; col < 11; col += 1) {
tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
}
tableString += "</tr>";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
This is how to loop through a javascript object and put the data into a table, code modified from #Vanuan's answer.
<body>
<script>
function createTable(objectArray, fields, fieldTitles) {
let body = document.getElementsByTagName('body')[0];
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let thr = document.createElement('tr');
for (p in objectArray[0]){
let th = document.createElement('th');
th.appendChild(document.createTextNode(p));
thr.appendChild(th);
}
thead.appendChild(thr);
tbl.appendChild(thead);
let tbdy = document.createElement('tbody');
let tr = document.createElement('tr');
objectArray.forEach((object) => {
let n = 0;
let tr = document.createElement('tr');
for (p in objectArray[0]){
var td = document.createElement('td');
td.setAttribute("style","border: 1px solid green");
td.appendChild(document.createTextNode(object[p]));
tr.appendChild(td);
n++;
};
tbdy.appendChild(tr);
});
tbl.appendChild(tbdy);
body.appendChild(tbl)
return tbl;
}
createTable([
{name: 'Banana', price: '3.04'}, // k[0]
{name: 'Orange', price: '2.56'}, // k[1]
{name: 'Apple', price: '1.45'}
])
</script>
<style>
body{
background: radial-gradient(rgba(179,255,0.5),rgba(255,255,255,0.5),rgba(0,0,0,0.2));
text-align: center;
}
#name{
margin-top: 50px;
}
.input{
font-size: 25px;
color: #004d00;
font-weight: 700;
font-family: cursive;
}
#entry{
width: 150px;
height: 40px;
font-size: 23px;
font-family: cursive;
background-color: #001a66;
color: whitesmoke;
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
margin: 20px;
}
table{
border-collapse: collapse;
width: 50%;
margin: 50px auto;
background-color: burlywood;
}
table,th,td{
border: 2px solid black;
padding:5px;
}
th{
font-size: 30px;
font-weight: 700;
font-family: Arial;
color: #004d00;
}
td{
font-size: 25px;
color: crimson;
font-weight: 400;
font-family: Georgia;
}
.length{
width: 20%;
}
</style>
<body>
<!-- Code to get student details -->
<div id="container" >
<div class="input">
Name: <input type="text" id="name" class="length" placeholder="eg: Anil Ambani"/>
</div>
<div class="input">
Email: <input type="text" id="mail" class="length" placeholder="eg: AnilAmbani#gmail.com"/>
</div>
<div class="input">
Phone: <input type="text" id="phn" class="length" placeholder="eg: 9898989898"/>
</div>
<div class="input">
SLNO: <input type="number" id="sln" class="length" placeholder="eg: 1"/>
</div>
<br>
<button id="entry"> I/P ENTRY</button>
</div>
<table id="tabledata">
<tr>
<th> Name</th>
<th> Email</th>
<th> Phone</th>
<th> Slno</th>
</tr>
</table>
</body>
<script>
var entry = document.getElementById('entry');
entry.addEventListener("click",display);
var row = 1;
function display(){
var nam = document.getElementById('name').value;
var emal = document.getElementById('mail').value;
var ph = document.getElementById('phn').value;
var sl = document.getElementById('sln').value;
var disp = document.getElementById("tabledata");
var newRow = disp.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = nam;
cell2.innerHTML = emal;
cell3.innerHTML = ph;
cell4.innerHTML = sl;
row++;
}
</script>
I wrote a version that can parse through a list of objects dynamically to create the table as a string. I split it into three functions for writing the header columns, the body rows, and stitching it all together. I exported as a string for use on a server. My code uses template strings to keep things elegant.
If you want to add styling (like bootstrap), that can be done by adding more html to HEAD_PREFIX and HEAD_SUFFIX.
// helper functions
const TABLE_PREFIX = '<div><table class="tg">';
const TABLE_SUFFIX = '</table></div>';
const TABLE_HEAD_PREFIX = '<thead><tr>';
const TABLE_HEAD_SUFFIX = '</tr></thead>';
const TABLE_BODY_PREFIX = '<tbody><tr>';
const TABLE_BODY_SUFFIX = '</tr></tbody>';
function generateTableHead(cols) {
return `
${TABLE_HEAD_PREFIX}
<td>#</td>
${cols.map((col) => `<td>${col}</td>`).join('')}
${TABLE_HEAD_SUFFIX}`;
}
function generateTableBody(cols, data) {
return `
${TABLE_BODY_PREFIX}
${data.map((object, index) => `
<tr><td>${index}</td>
${cols.map((col) => `<td>${object[col]}</td>`).join('')}
</tr>`).join('')}
${TABLE_BODY_SUFFIX}`;
}
/**
* generate an html table from an array of objects with the same values
*
* #param {array<string>} cols array of object columns used in order of columns on table
* #param {array<object>} data array of objects containing data in a single depth
*/
function generateTable(data, defaultCols = false) {
let cols = defaultCols;
if (!cols) cols = Object.keys(data[0]); // auto generate columns if not defined
return `
${TABLE_PREFIX}
${generateTableHead(cols)}
${generateTableBody(cols, data)}
${TABLE_SUFFIX}`;
}
Here's an example use:
const mountains = [
{ height: 200, name: "Mt. Mountain" },
{ height: 323, name: "Old Broken Top"},
]
const htmlTableString = generateTable(mountains );
var btn = document.createElement('button');
btn.innerHTML = "Create Table";
document.body.appendChild(btn);
btn.addEventListener("click", createTable, true);
function createTable(){
var div = document.createElement('div');
div.setAttribute("id", "tbl");
document.body.appendChild(div)
document.getElementById("tbl").innerHTML = "<table border = '1'>" +
'<tr>' +
'<th>Header 1</th>' +
'<th>Header 2</th> ' +
'<th>Header 3</th>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>'
};
var div = document.createElement('div');
div.setAttribute("id", "tbl");
document.body.appendChild(div)
document.getElementById("tbl").innerHTML = "<table border = '1'>" +
'<tr>' +
'<th>Header 1</th>' +
'<th>Header 2</th> ' +
'<th>Header 3</th>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>' +
'<tr>' +
'<td>Data 1</td>' +
'<td>Data 2</td>' +
'<td>Data 3</td>' +
'</tr>'
Here is an example of drawing a table using raphael.js.
We can draw tables directly to the canvas of the browser using Raphael.js
Raphael.js is a javascript library designed specifically for artists and graphic designers.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='panel'></div>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
paper = new Raphael(0,0,500,500);// width:500px, height:500px
var x = 100;
var y = 50;
var height = 50
var width = 100;
WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)
{
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;
}
function WriteTableRow(x,y,width,height,paper,TDdata)
{ // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.
var TD = TDdata.split(",");
for (j=0;j<TD.length;j++)
{
var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});// draw outline
paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
x = x + width;
}
}
</script>
</html>
Please check the preview image: https://i.stack.imgur.com/RAFhH.png
function creatTable(row = 10, col = 6) {
var table = "<table style ='margin-left: auto;margin-right: auto; border-collapse: collapse; width: 70%; ' >";
document.write(table);
for (var h = 1; h < parseInt(col); h++) {
th = "<th style='border: 3px solid #ddd;padding: 8px; padding-top: 12px;padding-bottom: 12px;text-align: center;background-color: #f5cf78;color: white;'>" + "I\'m Header";
document.write(th);
th += "</th>";
}
for (var i = 1; i < parseInt(row); i++) {
tr = "<tr style='background: ; :hover{background: #ffff99}'>";
document.write(tr);
tr += "</tr>";
for (var j = 1; j < parseInt(col); j++) {
td = "<td style='border: 3px solid #ddd; padding: 8px;'>" + "I\'m cell no." + i + "," + j;
document.write(td);
td += "</td>";
}
tr += "</tr>";
}
table = "</table>";
}
console.log(creatTable())
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>JavaScript...</h1>
<h2>Hello!</h2>
<h3>This Table Created by JavaScript ©
<font color=# ff0026>Geologist / Mohamed Yasser</font>
</h3>
<script src="main.js"></script>
</body>
</html>
You might find this very helpful
<html>
<head>
<title>tABLE IN JS</title>
</head>
<body>
<table border = "1">
<tr>
<th>Plug-in Name</th>
<th>Filename</th>
<th>Description</th>
</tr>
<script language = "JavaScript" type = "text/javascript">
for (i = 0; i<3; i++) {
document.write("<tr><td>");
document.write("Hello world");
document.write("</td><td>");
document.write("Hello China");
document.write("</td><td>");
document.write("Hello USA");
document.write("</td></tr>");
}
</script>
</table>
</body>
</html>
So you create the table head according to the number of columns you want and the rows will depend on the number you specified in the iteration..... i.e this one will be 3.

Categories