I have a 2d array that populates a table. Is there a way to insert a column all the way to the left?
//function to create the table
function createTable(tableData) {
var table = document.createElement('table');
var row = {};
var cell = {};
tableData.forEach(function (rowData) {
row = table.insertRow(-1);
rowData.forEach(function (cellData) {
cell = row.insertCell();
cell.textContent = cellData;
let cellVal = cellData;
//make cells different shades of green and red for pos/neg (based on %)
if (cellVal > 0) {
cell.style.backgroundColor = '#00e100';
} else if (cellVal < 0) {
cell.style.backgroundColor = 'red';
}
});
});
document.body.appendChild(table);
}
createTable(transpose_array);
I dont want to add values to the table because of the color conditions, Id just like to add headers to each row on the y-axis of the table using values from an array I have.
Image is below:
The forEach() callback gets a second argument containing the array index, you can use this to index into the headings array, and insert that as the first cell in each row.
//function to create the table
function createTable(tableData, row_headings) {
var table = document.createElement('table');
var row = {};
var cell = {};
tableData.forEach(function(rowData, i) {
row = table.insertRow(-1);
cell = row.insertCell();
cell.textContent = row_headings[i];
rowData.forEach(function(cellData) {
cell = row.insertCell();
cell.textContent = cellData;
let cellVal = cellData;
//make cells different shades of green and red for pos/neg (based on %)
if (cellVal > 0) {
cell.style.backgroundColor = '#00e100';
} else if (cellVal < 0) {
cell.style.backgroundColor = 'red';
}
});
});
document.body.appendChild(table);
}
createTable(transpose_array, price_array);
Related
I am building a table with JavaScript. If you check the link you can see it is all in one column, but I need the name. prices, and images in separate columns. I am honestly not sure where to start to do this, so I'm looking for some help.
https://jsfiddle.net/wL28gd10/
JS
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto =
["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table"),
row = table.insertRow();
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
// Brreak into next row
var next = i + 1;
if (next%perrow==0 && next!=itemName.length) {
row = table.insertRow();
}
}
// Loop through itemPrice array
for (var i = 0; i < itemPrice.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPrice.length) {
row = table.insertRow();
}
}
// Loop through itemPhoto array
for (var i = 0; i < itemPhoto.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPhoto.length) {
row = table.insertRow();
}
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
Just create all of your columns in one loop, like:
for (var i = 0; i < itemName.length; i++) {
var row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Add cell
cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
You only really need one loop.
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto = ["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table");
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
let row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
table { border-collapse: collapse; }
table tr td {
border: 1px solid black;
padding: 10px;
background-color: white;
}
<div id="menu-table"></div>
I need help creating a combo-box in my js file for the timesheet application? So there is an add row button in the timesheet which will create a new Row. I would like to have a drop-down + input for the first column in the row which will list the customers. Initially, there is no row in the timesheet application user will need to add a row to submit the timesheet. After clicking the add row it will create a row in which I would like to have a drop-down in the "Project Code" section which lists Internal Timesheet Application our customers. The JS code I used to create the table is as follows:
var arrHead = new Array(); // array for header.
arrHead = ['', 'Project Code', 'Project Description', 'Billable Hours'];
// first create TABLE structure with the headers.
function createTable() {
var empTable = document.createElement('table');
empTable.setAttribute('id', 'empTable'); // table id.
var tr = empTable.insertRow(-1);
for (var h = 0; h < arrHead.length; h++) {
var th = document.createElement('th'); // create table headers
th.innerHTML = arrHead[h];
tr.appendChild(th);
}
var div = document.getElementById('cont');
div.appendChild(empTable); // add the TABLE to the container.
}
//Creating a drop-downlist for Project Code
// now, add a new to the TABLE.
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // table row count.
var tr = empTab.insertRow(rowCnt); // the table row.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // table definition.
td = tr.insertCell(c);
if (c == 0) { // the first column.
// add a button in every new row in the first column.
var button = document.createElement('input');
// set input attributes.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// add button's 'onclick' event.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
else {
// 2nd, 3rd and 4th column, will have textbox.
var ele = document.createElement('input'); //I would like create a combo-box for 2nd Column
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
// delete TABLE row function.
function removeRow(oButton) {
var empTab = document.getElementById('empTable');
empTab.deleteRow(oButton.parentNode.parentNode.rowIndex); // button -> td -> tr.
}
// function to extract and submit table data.
function submit() {
var myTab = document.getElementById('empTable');
var arrValues = new Array();
// loop through each row of the table.
for (row = 1; row < myTab.rows.length - 1; row++) {
// loop through each cell in a row.
for (c = 0; c < myTab.rows[row].cells.length; c++) {
var element = myTab.rows.item(row).cells[c];
if (element.childNodes[0].getAttribute('type') == 'text') {
arrValues.push("'" + element.childNodes[0].value + "'");
}
}
}
// The final output.
document.getElementById('output').innerHTML = arrValues;
}
//console.log (arrValues); // you can see the array values in your browsers console window. Thanks :-)
Here is the solution to my Problem:
To make a combo-box for only one column
// now, add a new to the TABLE.
function addRow() {
var empTab = document.getElementById('empTable');
var rowCnt = empTab.rows.length; // table row count.
var tr = empTab.insertRow(rowCnt); // the table row.
tr = empTab.insertRow(rowCnt);
for (var c = 0; c < arrHead.length; c++) {
var td = document.createElement('td'); // table definition.
td = tr.insertCell(c);
if (c == 0) { // the first column.
// add a button in every new row in the first column.
var button = document.createElement('input');
// set input attributes.
button.setAttribute('type', 'button');
button.setAttribute('value', 'Remove');
// add button's 'onclick' event.
button.setAttribute('onclick', 'removeRow(this)');
td.appendChild(button);
}
**else if (c==1) {**\\ Defining the first column with a drop-down
var values = ["","Tiger", "Dog", "Elephant"];
var select = document.createElement("select");
select.name = "pets";
select.id = "pets";
for (const val of values) {
var option = document.createElement("option");
option.value = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
td.appendChild(select);
}
else{
// 3rd and 4th column, will have textbox.
var ele = document.createElement('input');
ele.setAttribute('type', 'text');
ele.setAttribute('value', '');
td.appendChild(ele);
}
}
}
I have a table having data in JSON form fetch from local-disk, i read all the data using getJSON method and put into table on the other hand i store the json data into local-storage for edit and delete operations , i just want to add pagination so that i see limited records on my page. I have no idea how to make a pagination on table How can i do this through jquery?
Javascript
$.getJSON("2-fedtest.json", function(data) {
if (localStorage.getItem("2_fedtest_json_file") == undefined) {
trans = data.listing_data;
localStorage.setItem('2_fedtest_json_file', JSON.stringify(trans));
} else {
trans = JSON.parse(localStorage.getItem("2_fedtest_json_file"));
}
response(trans);
});
function response(e) {
let table = document.getElementById("transaction_table");
let row, cell, button;
for (let i = 0; i < e.length; i++) {
row = table.insertRow();
cell = row.insertCell();
cell.textContent = e[i].document_first_name;
cell = row.insertCell();
cell.textContent = e[i].email;
cell = row.insertCell();
cell.textContent = e[i].document_dob;
cell = row.insertCell();
cell.textContent = e[i].used_services_in_request;
cell = row.insertCell();
const detailbutton = document.createElement("button");
////////////// Detail Button///////////
detailbutton.id = i;
detailbutton.innerHTML = 'Detail';
$(detailbutton).click(function(e) {
var button_click_id = detailbutton.id;
});
cell.appendChild(detailbutton);
////////// Edit Button///////////////
cell = row.insertCell();
const editebutton = document.createElement("button");
editebutton.id = i;
editebutton.innerHTML = 'Edit';
$(editebutton).click(function(e) {
var button_click_id = detailbutton.id;
});
cell.appendChild(editebutton);
////////End Edit Button//////////////
//
///////Delete Button////////
cell = row.insertCell();
const deletebutton = document.createElement("button");
deletebutton.style.color = "#fff";
deletebutton.id = i;
deletebutton.style.background = "red";
deletebutton.innerHTML = 'Delete';
$(deletebutton).click(function(e) {
});
cell.appendChild(deletebutton);
}
});
Html
<table id="transaction_table" class="pagination">
<tr>
<th id="detail">Detail</th>
<th id="detail">Edit</th>
<th id="detail">Delete</th>
<tr>
</table>
If you have all the data already available to your program, then I’d imagine all you really need to do is hide all the elements except the first n, where n is the page size. Then add in a “next” button with an event listener that will hide the current n items while displaying the next n whenever clicked. A simple variable as a page number counter that increments when next is pressed and is used to index the relevant rows to show would work fine there. You can also add a “previous” button to do the opposite of the above.
I would like to loop through the cells in the second column of an html table, adding a link to the text in each cell. I have a generic base URL, with a hash that should be defined by an integer in the corresponding cell in the first column of the table.
For example, the text in first cell of the second column should link to:
http://test.example.com/foo.html#1
Where the #1 is defined by the integer in the first cell of the first column (1). Then repeat for each row, where the integer in each cell of the first column should be used for the hash.
Pure js or jquery would work. I have found this snippet of jquery, which seems like a good start for iterating through each cell in the second column:
$('#table1 td:nth-child(2)').each(function(elem) {
//do something with elem
});
Is this jquery method appropriate, and if so, how can I apply the links as described?
As a possible alternative, could I modify the function I use to create the table?:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
Since you are the one creating the table at the first place it is best to modify the code and render it correctly (as oppose to updating it later on client-side).
Based on your comments and clarification here is the updated code, storing the integer value of first column of each row to use it as url on second column:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
var theUrl = 'http://test.example.com/foo.html#'; //replace with real URL
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
var i = 1;
var numValue = '';
var content = '';
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
numValue = (i==1) ? cellData : numValue ;
if(i==2){
content = document.createElement('a');
content.setAttribute('href', theUrl + numValue);
content.innerText = cellData ;
}
else{
content = document.createTextNode(cellData);
}
cell.appendChild(content);
row.appendChild(cell);
i++;
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
You may change the following code:
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
to
for (var i=0; i<rowData.length;i++)
{
var cell = document.createElement('td');
if (i==1)
{
var link=document.createElement("a");
link.href="http://test.example.com/foo.html#"+(i+1);
link.text=rowData[i];
cell.appendChild(link);
}
else
cell.textContent=rowData[i];
row.appendChild(cell);
}
I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name