I'm new to javascript and HTML, and I am looking to dynamicaly create a table with a loop in javascript inside of a HTML file.
I have the code to create a table, but I am struggling to get it to increase by one cell each row.
I feel as though I need to add 1 my cell variable each time the for loop runs, I assume its something like cells++ but when ever I do this the html file wont load anything, any ideas on where to place it within my for loops? or am I totaly on the wrong path?
<script>
var table = "", rows = 1, cells = 1;
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 1; c <= cells; c++) {
table += "<td>" + c + "</td>"
}
table += "</tr>"
}
document.write("<table border =1>" + table + "</table>")
</script>
This is what I want it to look like:
In order to get "stairs" look-like table, the amounts of rows and cells should be equal. Example below is how to do it properly. In order to change amount of rows, change value of variable from 7 to what you want ;)
var table = "";
rows = 7;
for (var r = 0; r <= rows; r++) {
table += "<tr>";
for (var c = 1; c <= r; c++) {
table += "<td>" + c + "</td>";
}
table += "</tr>";
}
document.write("<table border =1>" + table + "</table>");
Related
I have a problem with the following code. I am trying remove rows from a table if that row does not contain the meat in the td. To clarify, when the function is called, it takes in 2. (Which is where the word meat can be found in the table)
Some of the rows do not contain the word meat, x = rows[i].getElementsByTagName("td")[a]; The word meat can be found in [a] of the row. I think the problem is with x.innerHTML, as I don't think it returns a value to compare to b.
Any help or leads are appreciated. Right now when the button is clicked to call the function, nothing happens.
function clearTable(a) {
var table, rows, switching, i, x, c, shouldSwitch;
table = document.getElementById("Invtable");
switching = true;
var b = "meat";
while (switching){
switching = false;
rows = table.getElementsByTagName("tr");
for (i = 0; i < (rows.length); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[a];
if(x.innerHTML.toLowerCase() != b){
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
table.deleteRow(i);
switching = true;
}
}
}
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td> <img src='CSV_Photos/" + array[i][j] + "' style ='width:250px;height:250px'>" + "<br>" //every 6th column is a picture
+ "<center> " + '<button id="btn" onClick="clickMe(\''+ array[i][1] + ',' + array[i][5] + '\')"> Buy / Add To Cart </button> </td>' + "</center>"; //button onclick takes (name+price)
} else {
table += "<td>" + array[i][j] + "</td>";
}
}
table += "</tr>";
}
Edit: Starting from the var table, that's how the table was made in javascript in a function.
The table code in html looks like this :
<tr><td>1000</td><td>Chicken</td><td>Meat</td><td>Perfect</td><td>Yes</td><td>$2.99</td><td>image</td> </tr>
The problem is you are passing the incorrect column number as the argument. You only have two td per row and the index starts at 0. So you have to pass 1 as your argument: clearTable(1).
I created a simple table so you can see your function works with the correct argument.
EDIT
I recreated my table to have 6 columns and I created a button that runs the function onClick.
var table = '<table id="Invtable"><tr><td>Food</td><td>chicken</td><td>Veggies</td><td>Ceral</td><td>Soda</td><td>Water</td></tr><tr><td>Food</td><td>water</td><td>Soda</td><td>Meat</td><td>Water</td><td>Ceral</td></tr><tr><td>Third-Food</td><td>Meat</td><td>Chicken</td><td>Ceral</td><td>Water</td><td>Soda</td></tr></table>';
var btn = '<button onClick="clearTable(1)">Meat</button>';
document.body.innerHTML = table + btn;
//clearTable(1);
function clearTable(a) {
var table, rows, switching, i, x, c, shouldSwitch;
table = document.getElementById("Invtable");
switching = true;
var b = "meat";
while (switching){
switching = false;
rows = table.getElementsByTagName("tr");
console.log(rows);
for (i = 0; i < (rows.length); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[a];
if(x.innerHTML.toLowerCase() != b){
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
table.deleteRow(i);
switching = true;
}
}
}
I created Html table using JavaScript. Its working perfectly, its giving me row and column perfectly. But I want to display the cell value
Javscript Code
var table ="";
var row = 2;
var cols = 2;
//var row =2,cols =4;
for(var r=0; r<row;r++)
{
table+='<tr>'; // open row
for (var c=1; c<=cols;c++)
{
table += "<td>"+ c+'</td>';
}
table+= "</tr>"; // close row
}
document.write("<table>"+ table + "</table>");
output
1 2
1 2
Wanted output. cell 2,1 would have "(2,1)" in it
1,1 2,1
1,2 2,2
What am I missing ? I try to give the for loop value but no success.
You can use table += <td>" + r + "," + c +'</td>
Say I have a dynamic table, something like this (just an example):
var table = '<table>';
for (var i=0; i<6; i++) {
table += '<tr>';
table += '<th>';
table += 'HEADER ' + i + '</th></tr>'
table += '<tr><td>one</td>';
table += '<td>two</td>';
table += '<td>three</td>';
table += '<td>four</td>';
table += '<td>five</td>';
table += '<td>six</td>';
table += '<td>seven</td>';
table += '<td>eight</td>';
table += '</tr>';
}
table += '</table>';
What I'd like to do is to take each header and its table data under the header and save each as a separate table. For example, the first table would be:
HEADER 0
1 2 3 4 5 6 7 8
The second table would be:
HEADER 1
1 2 3 4 5 6 7 8
etc...
NOTE: There's no guarantee that there's only one row under each header. Some may have multiple rows.
To get the first table I could do:
var indexval = $(table).find('tr:contains("1")').index();
var firstTable = $(table).find('tr:lt('+indexval+')');
$('#testarea').html(firstTable);
I'm aware I'm calling these "tables" and that may not be correct. But how to start at the "next" header and go the the one after that and save 'that' table? In the end I'd have a number of little tables I could print to the screen by calling their variable names.
Demo:
var table = '<table>';
for (var i = 0; i < 6; i++) {
table += '<tr>';
table += '<th>';
table += '<td>HEADER ' + i + '</td></th></tr>'
table += '<tr><td>one</td>';
table += '<td>two</td>';
table += '<td>three</td>';
table += '<td>four</td>';
table += '<td>five</td>';
table += '<td>six</td>';
table += '<td>seven</td>';
table += '<td>eight</td>';
table += '</tr>';
}
table += '</table>';
//$('#testarea').html(table);
var indexval = $(table).find('tr:contains("1")').index();
var firstTable = $(table).find('tr:lt(' + indexval + ')');
$('#testarea').html(firstTable);
td, th {
min-width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='testarea'></div>
EDIT: I ended up solving my own problem by just using a couple of arrays to store each section of the table (each header and its immediate relevant rows under it). The first for loop gets the index value of the header, and the second for loop selects out the table rows (header and associated cells under it). The "firstRow" variable selects just the first header and its rows, the 'lastRow' variable does the same with the last header and row(s). Apologies for not initially putting the question in clear terms. The question was just asking how to segment out a large table into pieces with each header and its relevant rows underneath and save them as separate variables. My thinking was this would clean up my pagination method I've currently got on my site. When a 'page up' or 'page down' is clicked, it just loads the appropriate variable in the div on the page.
var firstRow = "";
var test = [];
var indexVal = [];
for (var i=2; i<7; i++) {
indexVal[i] = $(table).find('tr:contains('+('MC' + ' ' + i)+')').index();
}
firstRow = $(table).find('tr:lt('+indexVal[2]+')');
lastRow = $(table).find('tr:gt('+((indexVal[6]) - 1)+')');
for (var j=1; j<7; j++) {
test[j] = $(table).find('tr:lt('+indexVal[j + 1]+'):gt('+((indexVal[j]) - 1)+')');
}
The only issue I had was not being able to integrate the first and last rows into the for loops. I had to make them separate hand coded variables. But it works.
JSFIDDLE
I am wondering how to create a function with a for loop which creates new cells / rows for the other for loop to call upon. The function should return newRow which should be a specified amount of cells. The idea is the html code displays 3 images per row, but if there is just 2 images then it only needs 2 cells. That is the first if / else statement.
Here is the code so far..
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '</td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
//specified as 3 per row
var NUMPERROW = 3;
//gets number from form text input
var num = document.getElementById("searchtxt").value;
function search(){
//var num = 4;
console.log(num);
//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) {
//displays a new row of 3
htmlStr += newRow(NUMPERROW);
}else { //less then 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.
*
*/
//this function i do not know how to write
function newRow(cellsToAdd){
/////?????????? should be a for loop return new Row for the for loop above
}
}
Here is a simple function if you don't want to pass the values you can leave content out.
function newRow(numberOfCells, content)
{
var result = '<tr>';
for(var i = 0; i < numberOfCells; i++)
result += '<td>' + content[i] + '</td>';
result += '</tr>';
return result;
}
I was hoping some would know how to tile a grid across. I have some code to get started
1 | 2
3 | 4
5 | 6
and in my ajax function
$.ajax({
complete:function(result) {
// in here i want to tile across two sets of td's for each tr
for(var i = 0; i < products.length; i++) {
$('#products').append('<tr><td>' + products[i].Title + '</td></tr>');
}
}
});
<table id="products"></table>
This works whatever the products size is (even or odd).
Hope with comments make it easy to understand
var table_body = '< tbody>';
for(var i = 0; i < products.length; i++) {
if(i%2==0)//if even we open a row
table_body += '<tr>';
//We always put a value
table_body += '<td>' + products[i].Title + '</td>';
if(i%2!=0 || (i==products.length-1))//if odd we close a row
table_body += '</tr>';
}
table_body += '< /tbody>';
$('#products').append(table_body);
Here is a sample code of what you are trying to achieve. You can optimize it to suit your needs. Fiddle
for(var i = 0, y=0; i < 10; i++){
if(y == 0){
$('table').html($('table').html() + '<tr>');
}
$('table').append('<td>' + i + '</td>')
y++;
if( y == 2 ){
y = 0;
$('table').html($('table').html() + '</tr>');
}
}
The simplest solution is to simply not use a table. Chances are if you're arranging data this way, it's not tabular data anyway. I recommend using display: inline-block on your elements and using an HTML element that makes sense for the data you're using, like a ul or li.
This will work for even or odd numbers of elements, fully tested.
var tbl = "";
for (var i = 0; i < products.length; ++i) {
if (i % 2 == 0) tbl += '<tr>';
tbl += '<td>' + products[i].Title + '</td>';
if (i % 2 == 1) tbl += '</tr>';
}
if (i % 2 == 1) tbl += '</tr>';
$("#products").append(tbl);
fiddle