insertRow not working in for loop in JS - javascript

$(function(){
$('#sizePicker').submit(function makeGrid(evt) {
$('#pixel_canvas').empty();
evt.preventDefault();
var row = $('#input_height').val();
var cell = $('#input_width').val();
var table = $('#pixel_canvas');
for(r = 0; r <= row; r++){
var addRow = table.insertRow(r)
for(c = 0; c <= cell; c++){
addRow.insertCell(c);
}
}
});
});
This is my code to add rows and cells based on input, but for some reason when I use .insertRow and .insertCell there's no output, but when I use .append the function works perfectly. Anyone know why?

You are treating table like it's in the dom but it is a jQuery element so that wouldn't work.
Try this
table.get(0).insertRow(r)

Related

How to print table rows data in console

I've created dynamic table rows using javascript for loop and I want to fire a click event
on row in a way that whenever user clicks on any row it should be visible in console log.
<tbody>
<script>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['col1']+"</td>");
document.write("<td>"+data[i]['col2']+"</td>");
document.write("<td>"+data[i]['col3']+"</td>");
document.write("<td>"+data[i]['col4']+"</td>");
document.write("<td>"+data[i]['col5']+"</td>");
}
</tbody>
</script>
I know there are many answers for this but I tried and none helping me and some prints as
undefined.
Here is what I tried:
var table = document.getElementById("tableID");
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
tableText(this);
};
}
}
Your javascript code looks correct to me but I think you're not placing it at correct place.
Try this:
<script>
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['col1']+"</td>");
document.write("<td>"+data[i]['col2']+"</td>");
document.write("<td>"+data[i]['col3']+"</td>");
document.write("<td>"+data[i]['col4']+"</td>");
document.write("<td>"+data[i]['col5']+"</td>");
}
function tableText(tableRow) {
var name = tableRow.childNodes[1].innerHTML;
var age = tableRow.childNodes[3].innerHTML;
var obj = {'name': name, 'age': age};
console.log(obj);
}
let tableData = document.getElementById('tableID').getElementsByTagName('tbody')[0];
for (let i = 0; i < tableData.rows.length; i++)
{
tableData.rows[i].onclick = function()
{
tableClicked(this);
};
}
function tableClicked(rowData) {
let msg = rowData.cells[0].innerHTML+'*'+rowData.cells[1].innerHTML+'*'+rowData.cells[2].innerHTML+'*'+rowData.cells[3].innerHTML+'*'+rowData.cells[4].innerHTML;
console.log(msg,data);
};
</script>
Your Javascript code looks correct to me, and assuming tableText = console.log printed the correct row for me when I used it on a table.
Although I noticed in your table creation code that you are not closing your table row with </tr>.
for(var i=0;i<data.length;i++){
document.write("<tr>");
document.write("<td>"+data[i]['col1']+"</td>");
document.write("<td>"+data[i]['col2']+"</td>");
document.write("<td>"+data[i]['col3']+"</td>");
document.write("<td>"+data[i]['col4']+"</td>");
document.write("<td>"+data[i]['col5']+"</td>");
document.write("</tr>");
}

How to get innerHTML of td in dynamically populated table in JavaScript

I created a table and populated values from an array, so I have 5x5 table, where each td will be filled with a word. The word come from array memo and all the code below works fine.
var myTableDiv = document.getElementById("results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
//TABLE ROWS
for (i = 0; i < this.memo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < this.memo[i].length; j++) {
var td = document.createElement('TD');
td.onclick = function () {
check();
}
td.appendChild(document.createTextNode(this.memo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
I have one question : I would like to click on the cell and get the word, which belongs to the cell.
For this purpose I tried onclick as I created td element
td.onclick = function () {
check();
}
The function check should print the innerHTML of the cell, which was clicked
function check() {
var a = td.innerHTML;
console.log(a);
}
But it gives me always wrong text - the last one in the array, which was populated.
How could I solve it?..
You always get the last td in the array because the last value that was set to td was of the last cell. You need to add the a parameter, say event, to onclick's callback function, and then your clicked element will be referenced in event.target. Then you would be able to get it's innerHTML.
Here's why it's always giving you the first element: after the for (j = 0; ... loop is finished, the variable td will hold the value of the last element in the list. Then, when check is called, it accesses that same td variable pointing to the last element.
To solve this, you can add an argument to the function to accept a specific element and log that.
td.onclick = function () {
check(td);
};
// later...
function check(element) {
var html = element.innerHTML;
console.log(html);
}
I would pass the innerHTML in the click itself - please see working example below, with some mock data for memo.
var myTableDiv = document.getElementById("results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var memo = [
['joe', 'tom', 'pete'],
['sara','lily', 'julia'],
['cody','timmy', 'john']
]
table.border = '1'
table.appendChild(tableBody);
//TABLE ROWS
for (i = 0; i < this.memo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < this.memo[i].length; j++) {
var td = document.createElement('TD');
td.onclick = function () {
check(this.innerHTML);
}
td.appendChild(document.createTextNode(this.memo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
function check(a) {
console.log(a);
}
<div id="results">
</div>
you can try..
td.onclick = function () {
check();
}
to
td.onclick = function (evt) {
var html = evt.target.innerHTML;
console.log(html);
check(html); //to do something..
}

JavaScript : Delete dynamically created table

I am new to web development and struggling with deleting a dynamically created table.
Below is the JavaScript function to create the table when user clicks a button.
function DrawTable(data){
var oTHead = myTable.createTHead();
var oTFoot = myTable.createTFoot();
var oCaption = myTable.createCaption();
var oRow, oCell;
var i, j;
var heading = new Array();
heading[0] = "AAA";
heading[1] = "BBB";
heading[2] = "CCC";
heading[3] = "DDD";
var tableData = data.split(':');
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++)
{
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
// Insert rows and cells into bodies.
for (i=0; i < tableData.length; i++)
{
var oBody = oTBody0;
oRow = oBody.insertRow(-1);
var splitData = tableData[i].split(',');
for (j=0; j < splitData.length; j++)
{
oCell = oRow.insertCell(-1);
oCell.innerHTML = splitData[j];
}
}
}
The above code works perfectly and draws the table when user clicks on the button.
If user clicks on the button again it will draw the table again.
i.e., it will draw another header and all the rows all over again.
At this point I want to delete the existing header and rows and draw it all new.
I tried many things to delete the existing table, but nothing works.
Is there a way I can make sure that the table is not duplicated again?
UPDATE
The HTML part is:
<table id="myTable">
<tbody ID="oTBody0"></tbody>
</table>
ANOTHER UPDATE
I tried below and it worked.
oTHead.innerHTML = "";
oTBody0.innerHTML = "";
jQuery offers a .empty() function that you can use
$("#myTable").empty();
Or with javascript you can just set the innerHTML to empty
document.getElementById("myTable").innerHTML = "";
Just execute this function before you start trying to add new content to the table.
//$("#myTable").empty();
document.getElementById("myTable").innerHTML = "";
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++) {
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
Since you're using jQuery, just do this: $('#containerIdThatYourTableSitsIn').html('');
That will clear the html of whatever element your table sits in. Then just reload it.
Edit
As the comments have mentioned, .empty() is another option.

JS: getElementByID wildcard

I have a table and a button.
If i click the button, all <tr> which have an id starting with "tr" (in the example the first 3) should be set to display = "none";
Here is a Fiddle
Has anyone a Idea how i get this to work?
Give all the elements that have id="tr_NNNN" a distinct class, e.g. class="tr tr_NNNN". Then use the following loop:
var hide_trs = document.getElementsByClassName('tr_NNNN');
for (var i = 0; i < hide_trs.length; i++) {
hide_trs[i].style.display = "none";
}
You can simply iterate through your tr elements using the IDs:
function doJS() {
for(var i = 1; i <= 3; i ++) {
document.getElementById("tr_" + i).style.display="none";
}
}
You can't supply a wildcard to gEBI, but you can use the attribute starts with selector in qSA:
document.querySelectorAll("[id^='tr_']")[0].style.display="none";
I agree with using classes instead of IDs for this, but this should satisfy your original question:
function doJS() {
var rows = document.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if(row.getAttribute("id") && /^tr/.test(row.getAttribute("id"))){
row.style.display = 'none';
}
}
}
http://jsfiddle.net/eHSwJ/14/
And while this isn't a jQuery question, I would point out that by leveraging jQuery, this can be reduced to:
$('tr[id^="tr"]').css('display', 'none');

Support for muliple table ids through javascript method

I am using the following method to read header names in a table and put in excel. Could anyone let me know how to modify this to support multiple tables with header info and data.
i.e. how to modify to pass table id. "headers" is the id for "th" tag in code.
function write_headers_to_excel()
{
str="";
var myTableHead = document.getElementById('headers');
var rowCount = myTableHead.rows.length;
var colCount = myTableHead.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for(var i=0; i<rowCount; i++)
{
for(var j=0; j<colCount; j++)
{
str= myTableHead.getElementsByTagName("tr")[i].getElementsByTagName("th") [j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}
Your question is a bit vague, so I'm guessing at what you want. Assuming your current function works as is, you can just take out the hard-coding of the table's ID and pass it in as a parameter:
function write_headers_to_excel(tableID) {
var myTableHead = document.getElementById(tableID);
// rest of your function as is
}
Then call it once for each table, though that will create a new ExcelSheet for each table.
If the idea is for all of the tables to be added to the same ExcelSheet you can pass an array of table IDs to the function something like the following. I've kept the basic structure of your function but moved the variable declarations out of the loops (since that what JavaScript does behind the scenes anyway), deleted your ExcellApp variable since it wasn't used, and moved the getElementsByTagName call out of the inner loop.
write_headers_to_excel(["headers1","headers3","headers7","etc"]);
function write_headers_to_excel(tableIDs) {
var myTableHead,
rowCount,
cols,
t,
i,
j,
rowOffset = 1,
ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for (t=0; t < tableIDs.length; t++) {
myTableHead = document.getElementById(tableIDs[t]);
rowCount = myTableHead.rows.length;
for(i=0; i<rowCount; i++) {
cols = myTableHead.rows[i].getElementsByTagName("th");
for(j=0; j < cols.length; j++) {
ExcelSheet.ActiveSheet.Cells(i+rowOffset,j+1).Value = cols[j].innerHTML;
}
}
rowOffset += rowCount;
}
}
(No, I haven't tested it.)
You can get all tr elements by tag name
var rows = document.getElementsByTagName('tr');// get all rows of all tables
var table=0, TableRow=0;
for (i = 0; i < rows.length; i++) {
row = rows[i];
if (row.parentNode.tagName != 'THEAD' && row.parentNode.tagName != 'thead') {
table=table+1;
// do something here for headers
} else if (row.parentNode.tagName != 'TBODY' && row.parentNode.tagName != 'tbody')
{
TableRow=TableRow+1;
//do something here for rows
}
}

Categories

Resources