I am trying to make a matrix table by combining values from array. First array holds information about user for specific day. Second array holds list of users, third array holds days in month.
First I get data from api.
var odgovor = JSON.parse(http.responseText);
dataSetMoj = odgovor.urvPoDanuZaMjesec;
dataSetMojUposlenik = odgovor.uposlenici;
Get days for month
var mjesecImaDana = getDaysInMonth(1,2018);
var daniMjeseca = [];
for (i = 1; i <= mjesecImaDana; i++) {
daniMjeseca.push([i]);
}
Then I create table header
var k = '<thead>';
k +='<tr><th style="background-color: #f8f7f7" >' + rb + '</th>';
k +='<th style="background-color: #f8f7f7" >' + up + '</th>';
daniMjeseca.forEach(function(daysInmonth){
k += '<th style="background-color: #f8f7f7"> '+ daysInmonth +'</th>';
});
k += '</tr></thead>';
Table header display correct information, as could be seen in img.
Array rezultati holds information about each user on specific day
var rezultati = [];
for(i = 0;i < dataSetMoj.length; i++){
rezultati.push(dataSetMoj[i].ime+'-'+dataSetMoj[i].datum+'-'+dataSetMoj[i].urv);
}
Then I create table body, In table body I should match user with date.
k += '<tbody>'
for(i = 0;i < dataSetMojUposlenik.length; i++){
k+='<tr>';
k+='<td> ' + a++ + '</td>';
k+='<td> ' + dataSetMojUposlenik[i].ime + '</td>';
daniMjeseca.forEach(function(daysInmonth){
var dataSetVar = dataSetMojUposlenik[i].ime +'-'+daysInmonth;
//here I should check if variable 'datSetVar' is set in array rezultati, if yes I should print dataSetMoj[i].urv from rezultati
if(rezultati == dataSetVar ){
k+='<td> ' + dataSetMoj[i].urv + '</td>'; // It does not work, but I have no idea. I could not find solution any hint would help me.
}
else{
k+='<td> ' + c + '</td>';
}
});
k+='</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
Array rezultati holds three element dataSetVar two. I am not able to make comparison got wrong answers.
I have maybe weird question, but it is very important to me to solve this.
I have table wich is not with stable amount of rows and columns, so i put the += operator to create cells, rows and etc. Now i need to identify every cell, but i don't understand how i can do it in this situation.
function drawBoard(board) {
var t="";
t="<table border: 2px >";
var x,y;
for(x=0; x<board.length; x++){
t+="<tr>";
for(y=0; y<board.length; y++){
t+="<td class='tablecell' onclick=''>X</td>"
}
t+="</tr>";
}
t+="</table>";
}
By identify a cell I'm assuming you would like to reference them later in different part of the code.
You could achieve it by giving your rows and cells classes and/or ids.
For a row, for example:
t += '<tr id="tr-' + x + '">';
for a cell
t += '<td class="tablecell tr-' + x + ' col-' + y + '" onclick="" id="td-' + x + '-' + y + '">X</td>'
Then rows can be referenced by #tr-x and cells #tr-x > td, and all specific columnd .col-y
As Matheus Avellar mentioned, added id to a cell as well in case you want to reference a particular cell on a grid using #td-x-y
You are able to use:
const cells = document.getElementsByClassName('tablecell')
Or you can collect every cell on the stage of creation, for example:
const cells = [];
for (let i = 0; i < board.length){
for (let j = 0; j < board.length){
const cell = document.createElement('td');
cells.push(cell);
}
}
You can set the id of each one equal to your 'y' variable.
Something like:
function drawBoard(board) {
var t = "";
t = "<table border: 2px >";
var x, y;
for (x = 0; x < board.length; x++) {
t += "<tr>";
for (y = 0; y < board.length; y++) {
t += `<td id="table-${y}" class='tablecell' onclick=''>X</td>`
}
t += "</tr>";
}
t += "</table>";
}
Using a bit of ES6 template literals, you can set tie your ID to your 'Y' variable since it's an incrementing number.
I want to produce a table with Javascript. I want to give it a number and that's how many cells are created. There are always to be 3 columns however (3 pictures per row)
Could someone help me out with this? I think I need to use the modulus operator but I am unsure of how to use it correctly.
I do not want any extra cells. I can calculate the rows without issue but I don't want extra cells for those rows if that makes sense. So once the cells have been made that row ends even if it's 1 or 2 cells short.
I have this at the moment:
rows = ?? //Not sure how to calculate this
columns = 3;
str = "";
str += '<table border="1" cellspacing="1" cellpadding="5">';
for(i = 0; i < rows; i++){
str += '<tr>';
for (j = 0; j < columns; j++){
str += '<td>' + (i + j) + '</td>';
}
str += '</tr>';
}
str += '</table>';
Say if u have number of pictures as numPictures:-
Then
var numRows = Math.ceil(numPictures/3);
I hope the following code that what you want.
var numOfPics = 100; // Number of Pictures
var columns = 3, rows = Math.ceil(numOfPics / columns), content = "", count = 1;
content = "<table border='1' cellspacing='1' cellpadding='5'>";
for (r = 0; r < rows; r++) {
content += "<tr>";
for (c = 0; c < columns; c++) {
content += "<td>" + count + "</td>";
if (count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
count++;
}
content += "</tr>";
}
content += "</table>";
document.body.innerHTML = content; // insert `content` value into body of page
You know how many cells there are. So you divide the number of cells by the number of columns to get the number of rows. Math.ceil() rounds up in case there are not the exact amount of cells to fill a row.
rows = Math.ceil(total_num_cells / 3);
Question : I have to dynamically display the cell ,and each row must have 3 cell . I want to find how many rows it needed and if user enters 7 the first two row display 3 cell each and third row will only display 1 cell.
code:
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '<td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
var NUMPERROW = 3;
function search(){
var num = document.getElementById('searchTxt').value;
//Loop Once per Row.
var htmlStr = '';
for (var i = 0; i < num ; i = i + NUMPERROW){
//htmlStr += '<tr>' + cell + cell + cell + '<tr>';
if(num - i >= NUMPERROW){
htmlStr += newRow(NUMPERROW);
}else{// less than 3 to display
htmlStr += newRow(num - i);
}
}
document.getElementById('thumbnails').innerHTML = htmlStr;
}
/*
* Returns the html for a new row.
* numToAdd: the number of cells to add for this row.
*/
function newRow(cellsToAdd){
}
If I understood your question correctly, you can get the number of cells you need to add by using
newRow = NUMPERROW - (num % NUMPERROW)
where % is the modulo operator: 7 % 3 is the reminder of 7 / 3, which is 1
I've tried everything I can find via google and nothing has worked correctly. Output is just a single row with all the contents of the array listed. What I need is a way to write the contents of an array but after 3 cells, automatically start a new line. I'll post the code I've made below as well as the question. (yes this is from an assignment. :( )
//***(8) place the words in the string "tx_val" in a table with a one pixel border,
//*** with a gray backgound. Use only three cells per row. Empty cells should contain
//*** the word "null". Show the table in the span block with id="ans8"
var count = i % 3;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
{
nrow += "</tr><tr>";
}
}
document.getElementById('ans8').innerHTML = out + nrow;
you need to print the tr's inside the table (annd add a </table>!):
var count = i % 3; // btw. what's this??
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += "<td>" + txArr[i] + "</td>";
count++;
if (count % 3 == 0)
out += "</tr><tr>";
}
out += "</table>";
document.getElementById('ans8').innerHTML = out;
Rather than try to write out the html, try manipulating the dom. It seems much more straightforward to me. Take a look at the following:
var row = table.insertRow();
msdn
mdc
var cell = row.insertCell();
msdn
mdc
var cellContent = document.createTextNode(txArr[i]);
msdn
mdc
cell.appendChild(cellContent);
msdn
mdc
For deciding when to start a new row, just use the modulus operator (%
msdn
mdc
) against i:
if (i % 3 == 0)
{
row = table.insertRow()
}
You'd end up with something like this:
var container = document.getElementById("ans8");
var t = container.appendChild(document.createElement("table"));
var row;
txArr.forEach(function (item, i)
{
if (i % 3 == 0)
{
row = t.insertRow()
}
row.insertCell().appendChild(document.createTextNode(item));
});
I'll leave a little for you to figure out - border, background color, getting the word "null" in there. It is your homework after all. :-)
Also, for older browsers you'll need to add Array.forEach in yourself.
I prefer using an array over concatination
var html = [];
html.push("<table><tr>");
var i = 0;
for (var k in txArr)
{
if(i>=3){
i=0;
html.push("</tr><tr>");
}
html.push("<td>" + txArr[k] + "</td>");
i++;
}
html.push("</tr></table>");
document.getElementById('ans8').innerHTML = html.join('');
// wrapped in function
function arrayToTable(a,cols){
var html = [];
html.push("<table><tr>");
var i = 0;
for (var k in a)
{
if(i>=cols){
i=0;
html.push("</tr><tr>");
}
html.push("<td>" + a[k] + "</td>");
i++;
}
html.push("</tr></table>");
return html.join('')
}
document.getElementById('ans8').innerHTML = arrayToTable(txArr, 3);
It might be a tad easier to accomplish with something like
buffer = "<table>";
for(var r = 0; r < 10; r++){
buffer += "<tr>";
for(var c = 0; c < 3 ; c++){
buffer += "<td>Cell: " + r + ":" + c + "</td>";
}
buffer += "</tr>";
}
buffer += "</table>";
document.getElementById("ans8").innerHTML = buffer;
That would create a table 30 rows long by 3 columns for each row.
you might be assigning values to "count" too early as you don't know what i is yet. and you are not spitting out the value of nrow anywhere... change it to out.
var count;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
{
out += "</tr><tr>";
}
}
document.getElementById('ans8').innerHTML = out + nrow;
Basically I would split it up into 3 functions, for readability and maintenance. These functions would consist of creating a cell, a row, and a table. This definitely simplifies reading the code. As I have not tested it, below is an example of what I would do.
function createTableCell(value) {
return value == null? "<td>NULL</td>":"<td>" + value + "</td>";
}
function createTableRow(array) {
var returnValue = "";
for (var i = 0; i < array.length; i++) {
returnValue = returnValue + createTableCell(array[i]);
}
return "<tr>" + returnValue + "</tr>";
}
function arrayToTable(array, newRowAfterNArrayElements) {
var returnValue = "<table>";
for (var i = 0; i < array.length; i = i + newRowAfterNArrayElements) {
returnValue = returnValue + createTableRow(array.split(i, (i + newRowAfterNArrayElements) - 1));
}
return returnValue + "</table>";
}
document.getElementById("ans8").innerHTML = arrayToTable(txArr, 3);
In addition this makes your code much more dynamic and reusable. Suppose you have an array you want to split at every 4 element. Instead of hardcoding that you can simply pass a different argument.
Here's a live example of doing this with DOMBuilder, and of using the same code to generate DOM Elements and an HTML String.
http://jsfiddle.net/insin/hntxW/
Code:
var dom = DOMBuilder.elementFunctions;
function arrayToTable(a, cols) {
var rows = [];
for (var i = 0, l = a.length; i < l; i += cols) {
rows.push(a.slice(i, i + cols));
}
return dom.TABLE({border: 1, bgcolor: 'gray'},
dom.TBODY(
dom.TR.map(rows, function(cells) {
return dom.TD.map(cells);
})
)
);
}
var data = [1, 2, null, 3, null, 4, null, 5, 6];
document.body.appendChild(arrayToTable(data, 3));
document.body.appendChild(
dom.TEXTAREA({cols: 60, rows: 6},
DOMBuilder.withMode("HTML", function() {
return ""+arrayToTable(data, 3);
})
)
);
Yes, you can build from scratch...but there's a faster way. Throw a grid at it. The grid will take data in a string, array, json output, etc and turn it into a proper HTML outputted table and will allow you to extend it with sorting, paging, filtering, etc.
My personal favorite is DataTables, but there are numerous others out there.
Once you get proficient, setting one of these up literally takes 5 minutes. Save your brain power to cure world hunger, code the next facebook, etc....