I have a simple table in HTML and I'm trying to edit a particular cell containing a number.
My arrays all have data in them and the table is created OK.
I want to have an edit box for the number in row3 col 2.
I have tried lots of things but nothing seems to work for me.
Needless to say I am a newbie at JS !!
Thanks,
Chris
Update - I have cracked it! more by luck than judgement.
This code does exactly what I want, but I'm finding it difficult to display for you. It works fine on codepenio.
<p id="dt"></p>
<table id="myTable">
<caption>Current values</caption>
<tr>
<th>Item</th>
<th>value</th>
<th>units</th>
</tr>
</table>
<!--
<input type="button" onclick="createRow()" value="Create Row" />
-->
<style>
table {
width: 400px;
}
th {
text-align: center;
}
table,
th,
td {
border: 1px solid #000;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
</style>
<script>
let numberOfrows = document.getElementById("myTable").rows.length;
let numberoftds = document.getElementById("myTable").rows[0].cells.length;
document.getElementById("dt").innerHTML = Date();
// All names including blanks are placed in array below P01 - P30 incl
pname_english =
"#cabinet model#Serial number#Face velocity#Face velocity alarm setpoint?#Laminar flow velocity#Laminar flow velocity alarm point?#Extract volume#Extract volume alarm point?#Filter pressure#Filter pressure alarm point?#filter saturation value#Hydrocarbon filter monitor#Formaldehyde filter condition monitor#UV tube hours run#Cabinet hours run#service due date#main carbon filter type#main carbon filter date fitted#";
let pnamearray = "pname_english";
pnamearray = pname_english.split("#");
name = "#p01AB200#P021234#P033.4#P041.2#P054.2#P064.8#P072.9#P083.2?#p092332";
let myarray = "name";
myarray = name.split("#");
units = "# # #m/s#m/s#m/s#m/s#Pa#Pa?# ";
let unitsarray = "units";
unitsarray = units.split("#");
console.log("Hello World!");
let col1 = "";
let col2 = "";
let col3 = "";
function createRow() {
//() causes the function to execute anyway!
var row = document.createElement("tr"); // create row node
col1 = document.createElement("td"); // create column node
col2 = document.createElement("td"); // create second column node
col3 = document.createElement("td"); // create second column node
row.appendChild(col1); // append first column to row
row.appendChild(col2); // append second column to row
row.appendChild(col3); // append second column to row
// col1.innerHTML = ""; // put data in first column
// col2.innerHTML = ""; // put data in second column
col3.innerHTML = ""; // put data in second column
var table = document.getElementById("myTable"); // find table to append to
table.appendChild(row); // append row to table
}
var table = document.getElementById("myTable");
var row = document.getElementsByTagName("tr")[0];
let l = 0;
for (i = 0; i < 8; i++) {
// add i rows to myTable
l = myarray[i].length;
col1.innerHTML = pnamearray[i]; // name column
col2.innerHTML = myarray[i].substring(3, l); //value column myarray[i];
col3.innerHTML = unitsarray[i]; //units column
if (i == 3) {
col2.innerHTML =
'<input type="number" id="tentacles" name="tentacles" min="10" max="100" value="20">';
}
createRow(); // create new row
}
</script>
</body>
document.getElementById("Table_ID").rows[YourRowIndex].cells.item(CellIndex)
RowIndex: Start from 0 to n-1( n is number of rows)
CellIndex: Start from 0 to m-1( m is number of cells per each row)
Related
I am building a gradebook web app. I wanted the app to have the ability to calculate grades upon pushing the Final button. However, it's not working for some reason:
var myTable = document.getElementById("myTable");
var r = 0;//how many rows; row index
var c = 1;//how many columns
//make a table
//table must be able to add rows
//table cells should be editable
//save changes?
//
//make a table head row
//all table columns must have a table head
//**
// var firstRow= myTable.insertRow(0);
function addRow(){
//make a new row
var row = myTable.insertRow(r);
//use a while loop to keep creating row cells until you reach last column
var i = 0;
while(i<c){
var cell = row.insertCell(i);
cell.innerHTML ="Students[i]";
i++;
}
r++;
}
function addColumn(){
//make new column
//increment column
var tHead = document.createElement("th");
var allRows= document.getElementsByTagName("tr");//get all rows
//put tHead in first row
allRows[0].append(tHead);
var dateTable = document.createElement("input");
dateTable.type = "date";
tHead.appendChild(dateTable);
//tHead.innerHTML = (c*2);
//add a new cell for each row
var j =1;
while(j<allRows.length){
var row2 = allRows[j];
var cell2 = row2.insertCell(c);
cell2.innerHTML = j;
j++;
}
c++;
f++;
//if there already id a final row, delete it
}
function unEdit(){
//go through every cell
//save input value to a variable
//remove the input cell
var valArray =[];
document.querySelectorAll("td>input").forEach(input => {
var num = parseInt(input.value);
valArray.push(num);
input.remove();
});
//put input value into innerhtml of td
var i = 0;
document.querySelectorAll("td").forEach(td =>{
td.innerHTML=valArray[i];
i++;
});
}
function editTable(){
var allCells = document.getElementsByTagName("td");
for(var k=0; k<allCells.length; k++){
var oldText= allCells[k];
var input = document.createElement("input");
input.type ="number";
input.max = 100;
input.min = 0;
//before making all cells input, save previous innerhtml to var,
//make it into a num instead of a string, and put that value into input
var prev = allCells[k].innerHTML;
prev = parseInt(prev);
input.value = prev;
allCells[k].innerHTML = "";
allCells[k].appendChild(input);
input.onblur;
}
}
function deleteRow(){
document.getElementById("myTable").deleteRow(1);
r--;
}
function deleteColumn(){
//go through each row
//delete cell at each index
var everyRow = document.getElementsByTagName("tr");
for(var p=0; p<everyRow.length; p++){
everyRow[p].deleteCell(-1);
}
c--;
var finalButton = document.getElementById("final");
finalButton.enabled = true;
}
//final grade column
function finalRow(){
//make a <thead>
//make a new cell going down
var finalHead = document.createElement("th");
finalHead.innerHTML= "Final Grade";
var theseRows = document.getElementsByTagName("tr");
theseRows[0].append(finalHead);
for(var t =1; t<theseRows.length; t++){
//go through every cell in the row
//total up the numbers and put it in the final cell
var finalTotal=0;
for(var e =1; e< theseRows[t].length; e++){
var numero = theseRows[t][e].value;
numero = parseInt(numero);
console.log(numero);
finalTotal += numero;
}
//add up the innerhtmls and put it in finalCell
var finalCell = theseRows[t].insertCell(-1);
finalCell.innerHTML = finalTotal;
}
c++;
//disable final button
var finalButton = document.getElementById("final");
finalButton.disabled = true;
var days = document.getElementById("days");
days.disabled = true;
}
addRow();
addColumn();
//make a table head row at the top
//maybe add a print button?
//add a final grade column
//make it so that final row stays final when add new students and days
//do final funtion inside of unEdit() at the end?????
table,td,th{
border: 1px solid black;
border-collapse: collapse;
}
<table id = "myTable"></table>
</script>
<button onclick ="addRow()">Students</button>
<button onclick ="addColumn()" id ="days">Days</button>
<button onclick="editTable()">Edit</button>
<button onclick="unEdit()">Unedit</button>
<button onclick="deleteRow()">Delete Row</button>
<button onclick="deleteColumn()">Delete Column</button>
<button onclick ="finalRow()" id ="final">Final</button>
<button>Print</button>
In the finalRow() function, I can't figure out why the total I keep getting is always 0. Why doesn't it add up the value of the cells? I wanted it to go through every row, get the number values from each cell and total it up. It seems like the issue is with the "numero" variable, but I'm not sure what the issue is.
the first error is because you forgot to declare the variable f, you declared only the variables r and c above.
the second is in the function DeleteRow() there is an indexing error because it finds a negative value when deleting the last row. If you don't even want him to delete the last row, I suggest using a Try-Catch to deal with this error.
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'm trying to create a table in javascript and put a header on it. I tried to incorporate the answer from this SO question but perhaps I didn't include it in the right place. The body of the table works perfectly, but the header appends as a bunch of text to the top instead of a nicely formatted header. Here is the code:
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
tbl.append(header)
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
It prints the rows and the columns correctly, but instead of interpreting the <tr><th> as HTML tags it just prints them out as text. I've also noticed that if the table text contains any HTML tags, like <strong> or <b>, they are returned as plain text as well. How can I make them be read as HTML. I have a CSS page as well but there's no reset or anything (intentionally) affecting the use of bold or tables. Here's my result
<tr><th>Country</th><th>City</th></tr>
1 Row 1 text
2 Row <b>2</b> text
Solution1
The way you are appending tbody rows, you can insert the heading as well. So instead of tbl.append(header) and defining the header string, you can use something like below:
results = {
weak_sent: [
"row 1 data",
"row 2 data"
],
weak_sent_num: [1,2]
}
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
// var header = '<tr><th>Country</th><th>City</th></tr>';
var header= document.createElement('thead')
var headingRow = document.createElement('tr')
var headingCell1 = document.createElement('td')
var headingText1 = document.createTextNode('country')
headingCell1.appendChild(headingText1)
headingRow.appendChild(headingCell1)
var headingCell2 = document.createElement('td')
var headingText2 = document.createTextNode('City')
headingCell2.appendChild(headingText2)
headingRow.appendChild(headingCell2)
header.appendChild(headingRow)
tbl.appendChild(header)
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// This is for the quick solution
// tbl.innerHTML = header
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
generate_table()
Solution2
As a quick solution you can use innerHTML property, as shown below.
results = {
weak_sent: [
"row 1 data",
"row 2 data"
],
weak_sent_num: [1,2]
}
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// This is for the quick solution
tbl.innerHTML = header
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
generate_table()
In the following code I need to display months and days in a table. I am able to display months but I can't display days in my table (it contains two headers months and days).
for (var i = 0; i <= result.length; i++) {
var doc = result[i];
var td = $("<td/>").html(doc.Months).data(doc);
var td2 = $("<td/>").html(doc.Days);
var tr = $("<tr>").html(td).append('</tr>');
table.append(tr);
}
<table id="mydemo5" class="mytdemo5" style="display:none;border-collapse: collapse; border-color:white;" border="1">
<tr><th colspan="2">Absence history </th></tr>
<tr><th>Months</th><th>Days</th></tr>
</table>
You are appending only first td, not td2, better to do it this way:
var tr = $("<tr>").appendTo(table); // no need of closing tag, it will be auto handled by jQuery
var td = $("<td>").html(doc.Months).data(doc).appendTo(tr); //No need to assign to var td if it doesn't have any other use
var td2 = $("<td>").html(doc.Days).appendTo(tr);
//table.append(tr) Not needed anymore
I am trying to create a table that is generated by user input data.
The table is reflecting a grid therfore I want the id of each cell to be the co ordinate of that grid. So the id of the bottom left cell would be id00. The top right cell id would be the maximum size of the grid that the user has entered.
So for example if data entered; x value=3; y value=3
this would produce the following table:
<table>
<tr><td id="id03"></td><td id="id13"></td><td id="id23"></td><td id="id33"></td></tr>
<tr><td id="id02"></td><td id="id12"></td><td id="id22"></td><td id="id32"></td></tr>
<tr><td id="id01"></td><td id="id11"></td><td id="id21"></td><td id="id31"></td></tr>
<tr><td id="id00"></td><td id="id10"></td><td id="id20"></td><td id="id30"></td></tr>
</table>
I have identified the basic concept for the code as you can see below:
<table>
Create a loop, initial value of r= 0; maximum value of r=y
r =0 <tr> create a secondary loop, initial value of n=0; maximum value of n = x; r remains constant for row
n=0; r= 0 <td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
….
n=3; r= 0* <td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
</tr>
….
r =3 <tr> n=0; r= 3 <td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
….
n=3; r= 3<td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
</tr>
</table>
I want to develop it in Javascript but I am new to the language and I am having trouble coding it.
Any help anyone could provide would be greatly appreciated.
Try this :
var x = 3; // value from input
var y = 4; // value from input
var table = document.getElementById("myTable");
for(var i = 0; i < y; i++) {
var row = table.insertRow(-1);
for(var j = 0; j < x; j++) {
var cell = row.insertCell(-1);
cell.id = "id" + (j) + (y - i - 1);
cell.innerHTML = cell.id;
}
}
Working example
Try something like this :
var rows = parseInt(document.getElementById('rows').value,10); // get input value
var cols = parseInt(document.getElementById('cols').value,10); // get input value
var table = document.createElement('table'); // create table element
table.border = "1"; // set some attributes
var prevrow; // used to store previous row element
for (var r = 0; r < (rows+1); r++) { // loop rows
var row = document.createElement('tr'); // create tr
for (var c = 0; c < (cols+1); c++) { // loop cols
var col = document.createElement('td'); // create td
col.id = 'id' + r + c; // set id of tr
col.innerHTML = col.id; // add some text
row.appendChild(col); // append td to tr
}
// if first tr then create append to table else insert before previous tr
if (prevrow) {
table.insertBefore(row, prevrow);
} else {
table.appendChild(row);
}
// store newly create tr
prevrow = row;
}
// append the new table to the output div
document.getElementById('output').appendChild(table);
Uses document.createElement(), element.appendChild() and element.insertBefore() to build the table
Working example here