JavaScript : Delete dynamically created table - javascript

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.

Related

How to fix randomly populating HTML table?

I'm getting the lat/lng of a location based on excel sheet input & outputting onto an HTML table. I'm able to get the correct coordinates; however, they do not output to the right column (they randomly populate the table, I want them next to their corresponding address). I discovered that the coordinates will populate correctly when I have the alert(newArray[n]); before the geocode searches.
Is there anyway I could fix this? Below is a snippet of my code:
var tblBodyObj = document.getElementById(tableID).tBodies[0];
for (var i = 0; i < tblBodyObj.rows.length; i++) {
for (var k = 1; k < rowLength; k++) {
var oCells = oTable.rows.item(k).cells;
var cellLength = oCells.length;
newArray[n] = '';
for (var j = 2; j < cellLength; j++) {
var cellVal = oCells.item(j).innerHTML;
//tblBodyObj.rows[i].insertCell(-1);
tblBodyObj.rows[i].insertCell(-1);
var value = cellVal + ' ';
newArray[n] = newArray[n] + value;
}
//alert(newArray[n]);
MQ.geocode().search(newArray[n])
.on('success', function(e) {
var results = e.result,
result,
latlng,
best;
result = results.best;
latlng = result.latlng;
var x = document.getElementById("grid1").rows[o].cells;
x[cellLength].innerHTML = latlng.lat;
var y = document.getElementById("grid1").rows[o].cells;
y[cellLength + 1].innerHTML = latlng.lng;
//alert(latlng);
o++;
n++;
});
i++;
}
}
}
Here's a trick to populate tables asynchronously... but it requires a different approach to inserting cells like what you're doing.
Build your full table beforehand in a string with a dummy image in each cell like this...
<td> <img style="display:none;" src="X" onerror="this.outerHTML=FetchSomeValue(this.row,this.col);"> </td>
And display the string to screen. As each image load FAILS, it'll call the function FetchSomeValue(Row,Col) and populate correctly by replacing the dummy image.
NB: I use this technique with images or iframes (depending) all the time, flawlessly.
Images and Iframes have a ONLOAD event which we can take advantage of.

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

Create a bookmarklet that can retrieve all max length of text box and then print the id and max length in a table

I want to create a bookmarklet by using javascript, which can retrieve max length of all text box in the page, and then print a table below the page with all id and max length indicated.
Here is my code, however it did not print anything.
javascript: (function() {
var body =document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
var tbdy = document.createElement('tbody');
var D = document,
i, f, j, e;
for (i = 0; f = D.forms[i]; ++i)
for (j = 0; e = f[j]; ++j)
if (e.type == "text") S(e);
function S(e) {
var l= document.getElementById(e.id);
var x = document.getElementById(e.maxlength);
var tr=document.createElement('tr');
var td1=document.createElement('td');
var td2=document.createElement('td');
td1.appendChild(document.createTextNode(l));
td2.appendChild(document.createTextNode(x));
tr.appendChild(td1);
tr.appendChild(td2);
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl);
})
This can actually be done much simpler than you have it.
Working jsfiddle: https://jsfiddle.net/cecu3daf/
You want to grab all of the inputs and run a loop over them. From this you can dynamically create a table and append it to the end of the document.body
var inputs = document.getElementsByTagName("input"); //get all inputs
var appTable = document.createElement("table"); //create a table
var header = appTable.createTHead(); //create the thead for appending rows
for (var i=0; i<inputs.length; i++) { //run a loop over the input elements
var row = header.insertRow(0); //insert a row to the table
var cell = row.insertCell(0); //insert a cell into the row
cell.innerHTML = inputs[i].maxLength; //input data into the cell
var cell = row.insertCell(0);
cell.innerHTML = inputs[i].id;
}
document.body.appendChild(appTable); //append the table to the document
To make it a bookmark, simply place the javascript: before hand. There is no need to encase it in a function. You can if you'd like to.

Storing the index of a for loop in javascript

I'm developing an android app with phonegap. I'm making an HTML table with some that with a for loop from localStorage. I need, for each row, to store the index i of the for to use it for retrieving an item from localStorage that has the name like the index. I have some code but the variable that i defined for that effect gets overwritten by the loop (of course). Here's the code:
<script language="javascript">
if(len != 0) {
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
var thead = document.createElement('th');
var row2 = document.createElement('tr'); // create a new row
var headText = document.createTextNode('Dados');
thead.scope = "col";
thead.appendChild(headText);
row2.appendChild(thead);
tableHead.appendChild(row2);
for (var i=0; i<len; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var a = document.createElement('a');
var cellText = document.createTextNode(localStorage.getItem('key' + i));
var xyz = "key" + i;
a.href = "alterar.html";
a.onclick = function() { doLocalStorage(xyz) };
a.appendChild(cellText);
cell.appendChild(a); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}}
</script>
</table>
Maybe i'm not explaining myself too well. If you need any more info please ask. Thanks in advance. Eva
try to put the key name in to a closure:
function wrapper(i) {
return function() {
doLocalStorage("key" + i)
}}
a.onclick = wrapper(i);
Not sure if I got your question right, but if you want to bind usage of a variable asynchronously when doing for loop then you should wrap it in a closure:
for(i = 1, c = arr.length; i < c; i++){
(function(i){
// i wont change inside this closure so bound events will retain i
$('#id'+i).click(function(){
alert(i); // Will alert the corresponding i
})
})(i);
}

issue in removing radio buttons using javascript in IE

I have a implementation where I am creating radio buttons dynamically, actually all the fields and values are dependent on each other like parent- child -grand child and so on. I am able to remove button but in Firefox using innerHtml but in IE it didn't worked. For IE, I got a diffrent code but that also doesn't worked properly below I am pasting code that generates it and removes it.
var idToUpdate = "radioID";
var nameToUpdate = "radioName";
var labelToUpdate = "labelText";
var tbody = document.createElement('tbody');
var row = document.createElement("tr")
var data1 = document.createElement("td")
var newRadio = document.createElement("input");
newRadio.type = "radio";
newRadio.id = idToUpdate;
newRadio.name = nameToUpdate;
newRadio.value = labelToUpdate;
if (defUpdater == 1)
newRadio.setAttribute('checked', 'checked');
newRadio.setAttribute("onclick", "javascript:dependentFieldsValue('" + idToUpdate + "');");
var data11 = document.createElement("td")
var newLabel = document.createElement("label");
newLabel.htmlFor = idToUpdate;
newLabel.id = idToUpdate;
newLabel.appendChild(document.createTextNode(labelToUpdate));
tbody.appendChild(row);
row.appendChild(data1);
data1.appendChild(newRadio);
row.appendChild(data11);
data11.appendChild(newLabel);
Node1.appendChild(row);
defUpdater = 0;
For loop in last is used for removing radio, we just get htmlelemnt using table ID and set the innerHTML to="".
for (var i = 0; i < len; i++) {
var node = documnet.getElemtsById("tableID"); // every button group have table and table is havin id.
Node.childNodes[i].innerHTML = ""; /// works for firefox// works fine
//Node.childNodes[i].Node.removeChild(Node.childNodes[i]);// works for IE but not properly
}
Please suggest.
I would use this construction:
var table = documnet.getElemtsById("tableID");
for (var i = 0; i < len; i++) {
var tr = table.childNodes[i];
tr.parentNode.removeChild(tr);
}

Categories

Resources