Is that possible to get values from dynamically created table after a button click?
Here is my code for creating a table with an input field:
function tableInsert(row,col){
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '1px solid black';
tbl.id="draw_table";
for(var i = 0; i < col; i++){
var tr = tbl.insertRow();
for(var j = 0; j < row; j++){
var input1 = document.createElement("input");
var td = tr.insertCell();
td.appendChild(input1);
td.style.border = '1px solid black';
}
}
body.appendChild(tbl);
console.log(tbl.id);
}
Here is the button click function. It gets the value of the table which is dynamically created:
$("#calculate").click(function(){
var table = document.getElementById('draw_table');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
console.log(table.rows[r].cells[c].value);//value is undefined . is it right way to get the value
}
}
});
your code retrieve td element while you need value of input tag!
change your code to this:
$("#calculate").click(function(){
var table = document.getElementById('draw_table');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
console.log(table.rows[r].cells[c].children[0].value);
}
}
}
Related
I'm trying to give each cell of a table an identifier like in this photo
this is what I tried but it's not working:
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;// <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier;// <--------this is the problem
}
}
document.getElementById("main").appendChild(board);
}
First of all, instead of custom properties you should use data attributes and instead of the width and height attributes you should use CSS. Second, you were incrementing identifier by itself, so it wouldn't grow from 0.
const GRID_SIZE = 6;
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.dataset.identifier = identifier;
cell.innerText = identifier;
row.appendChild(cell);
identifier++;
}
}
document.getElementById("main").appendChild(board);
}
init();
main>table td {
width: 20px;
height: 20px;
}
<main id="main"></main>
Also, you don't need to store the coordinates of the cell, since you can calculate them from the identifier like this:
row = Math.floor(identifier / GRID_SIZE);
column = identifier % GRID_SIZE;
GRID_SIZE*i+j;
put it inside the cell using cell.innerHTML=GRID_SIZE*i+j;
function init(GRID_SIZE) {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0; // <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.innerHTML = GRID_SIZE * i + j;
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier; // <--------
}
}
document.getElementById("main").appendChild(board);
}
init(10)
<div id="main"></div>
I have to generate a sequence with a difference of 9. starting from 7. sequence should have 20 terms. I have tested my for loop and its working fine. Question is, how do I embedd this for loop in a table in javascript? Just want the table to have one column (sequence in for loop)
<script type="text/javascript">
var i;
var p;
for (i = 0; i < 20; i++) {
p = i * 9 + 7;
document.writeln(p + "<br>");
}
</script>
Use a loop to create the relevant HTML element objects and set their values within your Javascript:
var table = document.createElement("table");
var i;
var p;
for (i = 0; i < 20; i++) {
var row = document.createElement("tr");
var row_data = document.createElement("td");
p = i * 9 + 7;
row_data.innerHTML = p;
row_data.style = "border: 1px solid black";
row.appendChild(row_data);
table.appendChild(row);
}
document.body.appendChild(table);
Declare a table in html and give it an id
<table id="table"></table>
Then, get that table in your javascript and add one row, column in each iteration
<script type="text/javascript">
var i;
var p;
var table = document.getElementById("table");
for (i = 0; i < 20; i++) {
p = i * 9 + 7;
table.innerHTML = `${table.innerHTML}<tr><td>${p}</td></tr>`;
}
</script>
let table = '<table><tbody>';
for (let i = 0; i < 20; i++) {
table += (`<tr><td>${i}</td><td>${i * 9 + 7}</td></tr>`);
}
table += '</tbody></table>';
document.body.innerHTML = table;
Array.from(document.getElementsByTagName('td'))
.forEach((td) => {
td.style.border = '1px solid green';
td.style.width = '40px';
td.style.textAlign = 'right';
td.style.paddingRight = '20px';
});
Array.from(document.getElementsByTagName('table'))
.forEach((table) => {
table.style.border = '2px solid';
});
How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.
I am working on this table that as to be managed by the client. I want to know if is possible to change the color of the entire row when in the "Status" column he writes the word "vermietet".
In this case when the client write "vermietet" the rows that contains that word change background color in orange.
Any JS tips?
Thanks in adivce.
EDIT:
I tried this
<script>
jQuery(document).ready(function($){
$(document.body)var cols = document.getElementsByClassName('column-10');
for (var i = 0; i < cols.length; ++i) {
var col = cols[i];
if (col.innerHTML === 'vermietet') {
var parent = col;
while((parent = parent.parentElement).tagName !== 'TR');
var found = parent.childNodes;
for (var j = 0; j < found.length; ++j) {
var td = found[j];
if (td.tagName === 'TD') {
td.style.backgroundColor = 'orange';
}
}
}
}
});
</script>
Pure JS solution:
var cols = document.getElementsByClassName('column-10');
for (var i = 0; i < cols.length; ++i) {
var col = cols[i];
if (col.innerHTML === 'vermietet') {
var parent = col;
while((parent = parent.parentElement).tagName !== 'TR');
var found = parent.childNodes;
for (var j = 0; j < found.length; ++j) {
var td = found[j];
if (td.tagName === 'TD') {
td.style.backgroundColor = 'orange';
}
}
}
}
I am JavaScript/html beginner and currently I am dealing with following issue:
I have several input fields, which are filled by the user.
When he filled up the fields, he presses the button and several tables are created.
So far works everything fine.
BUT
If I update the information in the input field and press the button, the NEW tables are created (the previous tables stay and new are added below)
My idea was to make following:
I put the new tables in a separate div.
Every time I press the button, the div information is deleted and created again.
But as I am a beginner I don’t really know how to do it.
Can anyone help me?
Do you have a better idea?
My code
(...)
/part with the table creation/
var zaehler=0;
for (zaehler = 0; zaehler < n; zaehler++){
tableCreate(n,zaehler,a,b,c,d,e,f,g,h,i,j,k,l);
}}
/the table create function/`
<script>
function tableCreate(maxyear,s4italka, a,b,c,d,e,f,g,h,i,j,k,l) {
var imena = ["Выручка", "Управляющая кампания", "Профилактика", "Налог на Недвижимость", "Страховка", "Амортизация", "Тело кредита", "%-ные выплаты банку", "%-ные выплаты себе", "Доход",
"Налог (15%)", "Финансовый результат" ];
var dannie =[a,b,c,d,e,f,g,h,i,j,k,l];
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
tbl.style.width = '40%';
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
var trh = document.createElement('tr');
var th = document.createElement('th');
var m=s4italka+2015;
th.appendChild(document.createTextNode('Результат на '+m+ ' год'))
th.setAttribute ('colSpan','2');
trh.appendChild(th)
tbdy.appendChild(trh);
for (var i = 0; i < 12; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
if ((j % 2) != 0)
{td.appendChild(document.createTextNode(dannie[i]))}
else {
td.appendChild(document.createTextNode(imena[i]))}
tr.appendChild(td)
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
var p= document.createElement('p');
body.appendChild(p);
}
</script>
You have to remove the previous table first. Currently the code that you have keeps appending new table to the body only but all the previous elements still remain there.
To remove the previous table:
jQuery:
body.find("table").remove();
Javascript:
var tables = document.getElementsByTagName("table");
for (var i = 0; i < tables.length; i++) {
tables[i].remove();
}
You can insert the code above before the line body.appendChild(tbl)
Note: jQuery function remove() will not throw error even if the table does not exist at the time of executing the code.
function tableCreate(maxyear, s4italka, a, b, c, d, e, f, g, h, i, j, k, l) {
var imena = ["Выручка", "Управляющая кампания", "Профилактика", "Налог на Недвижимость", "Страховка", "Амортизация", "Тело кредита", "%-ные выплаты банку", "%-ные выплаты себе", "Доход",
"Налог (15%)", "Финансовый результат"];
var dannie = [a, b, c, d, e, f, g, h, i, j, k, l];
$('.myTabel').remove();
var body = document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
$(tbl).addClass('myTabel');
tbl.style.width = '40%';
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
var trh = document.createElement('tr');
var th = document.createElement('th');
var m = s4italka + 2015;
th.appendChild(document.createTextNode('Результат на ' + m + ' год'))
th.setAttribute('colSpan', '2');
trh.appendChild(th)
tbdy.appendChild(trh);
for (var i = 0; i < 12; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
if ((j % 2) != 0)
{ td.appendChild(document.createTextNode(dannie[i])) }
else {
td.appendChild(document.createTextNode(imena[i]))
}
tr.appendChild(td)
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
var p = document.createElement('p');
body.appendChild(p);
}