Spliting row of table according to table data - javascript

It's making table with data 1 to 31 numbers in it. Now I want, as soon as a row is filled with seven numbers, it should automatically add a new row & insert numbers in that & it should continue till table finish. I mean first it will insert from 1 to 7, then next row should be added & data begins with 8 & after 15 a new row again started. Something like a calendar.
See the code snippet below.
var myDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var tableHeader = "";
var tableData = "";
var tableRow = "";
for (j = 1; j < 32; j++) {
tableData += "<td>" + j + "</td>";
}
document.getElementById("days").innerHTML = tableData;
#days, th, td {
border: 1px solid black;
border-collapse: collapse;
}
#days {
width: 50%;
text-align: center;
}
<table id="days"></table>

Have an outer loop for controlling the rows, and an inner loop for adding each <td> element. You can control the values of elements in the inner loop by offsetting them based on a multiple of the index of the outer loop.
Basically, if j is the index of your inner loop, and i is the index of your outer loop, then take a multiple of i (in this case i*7) and offset the start of j by that. See code example below.
var myDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var tableHeader = "";
var tableData = "";
var tableRow = "";
for (var i=0; i<32/7; i++) {
var k = i * 7;
tableData += "<tr>";
for (var j = 1 + k; j <= 7 + k; j++) {
if (j > 31) break;
tableData += "<td>" + j + "</td>";
}
tableData += "</tr>";
}
document.getElementById("days").innerHTML = tableData;
#days, th, td {
border: 1px solid black;
border-collapse: collapse;
}
#days {
width: 50%;
text-align: center;
}
<table id="days"></table>

You can try this answer
counter=0;
tableData+='<tr>';
for(j=1; j<32; j++){
if(counter==7)
{
tableData+='</tr>';
counter=0;
}
tableData+= "<td>" + j + "</td>";
++counter;
}

Related

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>
`

Format result after looping object

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;
}

Removing the space between cells of a grid [duplicate]

This question already has answers here:
Space between <td>. Why and how can I remove?
(7 answers)
Closed 6 years ago.
I want to remove the spaces between the cells so that the grid looks kind of like graph paper. There is a small space between the cells right now and I would like to remove that that.
Here is that I have now:
function generateGrid(rows, cols) {
var grid = "<table>";
for (row = 1; row <= rows; row++) {
grid += "<tr>";
for (col = 1; col <= cols; col++) {
grid += "<td></td>";
}
grid += "</tr>";
}
return grid;
}
$("#tableContainer").append(generateGrid(5, 5));
$("td").click(function() {
var index = $("td").index(this);
var row = Math.floor((index) / 5) + 1;
var col = (index % 5) + 1;
$("span").text("That was row " + row + " and col " + col);
$(this).css('background-color', 'red');
});
td {
border: 1px solid;
width: 50px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Select a cell!</span>
<div id="tableContainer"></div>
In your CSS:
table {
border-collapse: collapse;
}
table {
border-collapse: collapse;
}
th, td {
padding: 0;
}

set dynamically colspan jquery

I'm setting table rows dynamically. When there are more than 4 rows, table is too big and I have to cut it.
The idea is, when there is 5th row coming, it goes into second column of previous row, so there are still 4 rows, where last row has 2 columns. And then I'm trying to set colspan="2" for the rows that have 1 col.
But the thing is it doesn't want to work. I'm stuck with that for 2 days now and i can't find any idea for it... Would really love to hear any tips from You. Thanks in advance.
I've tried also setting colspan="2" into generateTD() function - no effects so far.
var container = document.getElementById('container');
function generateTD(){
var output = '';
for(var i=1; i<7; i++){
output += '<tr>';
if(i<5){
output += '<td class="merged-col">Row#'+[i]+'</td>';
if(i>=4){
output += '<td>Row#'+[i]+'</td>';
}
}
output += '</tr>';
}
container.innerHTML = output;
}
generateTD();
$('.merged-col').attr('colspan', 2);
td{
border: 1px solid black;
padding: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="container"></table>
Just calculate rows and columns.
var container = document.getElementById('container');
function generateTD(){
var output = '';
for(var i=1; i<7; i++){
output += '<tr>';
if(i < 4){
output += '<td class="merged-col">Row#'+[i]+'</td>';
//if(i>=4){
// output += '<td>Row#'+[i]+'</td>';
//}
}
else{
output += '<td>Row#'+[i]+'</td>';
output += '<td>Row#'+[i]+'</td>';
}
output += '</tr>';
}
container.innerHTML = output;
}
generateTD();
$('.merged-col').attr('colspan', 2);
td{
border: 1px solid black;
padding: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="container"></table>

td widths are not applied on auto width table

Please look at this fiddle http://jsfiddle.net/LHsLM/1/.
I am trying to apply height and width to a auto width table using inline css as in the fiddle. But the styles are not applied.
html:
<div id="a"></div>
css:
div {
height:300px;
width:500px;
overflow:auto;
}
js:
var str = ["<table>"];
for (var i = 0; i < 100; i++) {
var tr = "<tr>";
for(var j = 0; j < 100; j++){
tr += "<td style='width:120px;height:40px'>" + j + "</td>";
}
tr+="</tr>";
str.push(tr);
}
str.push("</table>");
document.getElementById('a').innerHTML = str.join('');
Convert width to min-width of your td elements.
Sorry, that is not IE-8 compatible.
This method works for IE8 too:
function tablo(){
var str = ["<table>"];
for (var i = 0; i < 100; i++) {
var tr = "<tr>";
for(var j = 0; j < 100; j++){
tr += "<td><div style='width:120px;height:40px'>" + j + "</div></td>";
}
tr+="</tr>";
str.push(tr);
}
str.push("</table>");
document.getElementById('a').innerHTML = str.join('');
}

Categories