Hide Dynamically Added Columns/Fields - javascript

I have some dynamically created rows/columns. What I'd like to do is set a section of it (txtOffsetID) to be hidden. I tried this: txtOffsetID.setAttribute('type', 'hidden'); but it didn't work. I want to hide that entire column and any new columns added. I need it to work in IE. Thanks.
Sample code:
function addNewOffsetItem()
{
var iX = document.getElementById("txtOffsetIndex").value;
iX ++;
document.getElementById("txtOffsetIndex").value = iX;
var tbl = document.getElementById("tblOffsetDetail").getElementsByTagName("TBODY")[0];
var tr = document.createElement("TR");
tbl.appendChild(tr);
//This section should be hidden.
//txtOffsetID1
var tdID = document.createElement("TD");
tr.appendChild(tdID);
var p = document.createElement("P");
tdID.appendChild(p);
var txtOffsetID = document.createElement("input");
p.appendChild(txtOffsetID);
txtOffsetID.id = "txtOffsetID" + iX;
txtOffsetID.setAttribute('name','txtOffsetID' + iX);
**document.getElementById("colOffsetID").style.display="none";**
//This section should be visible.
//txtOffsetComments1
var tdComments = document.createElement("TD");
tr.appendChild(tdComments);
var p = document.createElement("P");
tdComments.appendChild(p);
var txtOffsetComments = document.createElement("textarea");
p.appendChild(txtOffsetComments);
txtOffsetComments.id = "txtOffsetComments" + iX;
txtOffsetComments.setAttribute('name','txtOffsetComments' + iX);
}
<table width="99%" border="1" cellpadding="1" cellspacing="1" id="tblOffsetDetail">
<colgroup>
<col id="colOffsetID">
<col id="colOffsetComments">
</colgroup>
<tbody>
<tr>
<td><input type="text" id="txtOffsetID" name="txtOffsetID"></td>
<td><p><textarea name="txtOffsetComments" cols="15" rows="3" id="txtOffsetComments"></textarea></p></td>
</tr>
</tbody>
</table>

created "tr" element can be hidden like this
tr.setAttribute('style', 'display: none;');
but in case you want to hide full column than you need to use colgroup table element
example
<table>
<colgroup>
<col id="colOne">
<col id="colTwo">
<col id="colThre">
</colgroup>
<tbody>
<tr>
<td>one</td>
<td>two</td>
<td>three</td>
</tr>
</tbody>
you can hide colTwo like this
document.getElementById('colTwo').style.display = 'none';
I hope this helps

Related

Add row into existing table

May I know how do I insert items into my table body? My code doesn't seems to work.
var tableRef = document.getElementById("myList").getElementsByTagName("tbody");
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = tableRef.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
getElementsByTagName returns an array. You need to append [0] to select the first element in the array.
You are also trying to use insertCell on tableRef, when you should be using it on newRow:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
To make it work, you need to:
1) Put [0] after .getElementsByTagName() like below, as this method returns an array of elements, unlike .getElementById(), which returns the first instance:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
2) Use the .insertCell() in the row you want the cell to be, in our case newRow, not on the table's tbody:
var newCell = newRow.insertCell(0);
Your correct JavaScript code should be:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
You can also check out the following snippet:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
#myList {
border: 1px solid black;
}
#empty {
border-bottom: 1px solid black;
}
<table id = "myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
<!--- This row is for adding a border-bottom line -->
<tr>
<td id = "empty" colspan ="3"></td>
</tr>
</thead>
<tbody>
</tbody>
</table>

submit button not working when i combine my codes

it was working on when i split them into two but when i combine them the save button isnt working i tried changing the document.getElementById to document.getElementByClassName but it stops the function of both here is the code
<html>
<head>
<body>
<div class="container">
<table class="table table-hover table-bordered" id = "table1">
<thead>
<tr>
<th><center>Item Name</center> </th>
<th><center>Brand</center> </th>
<th><center>Selling Price</center> </th>
<th><center>Quantity</center> </th>
</tr>
</thead>
<tbody id = tbody1>
<tr>
<td>Cake</td>
<td>Pastry</td>
<td>100</td>
<td>5</td>
</tr>
<tr>
<td>Wat</td>
<td>But</td>
<td>100</td>
<td>5</td>
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-hover table-bordered" id = "table2">
<thead>
<tr>
<th><center>Item Name</center> </th>
<th><center>Brand</center> </th>
<th><center>Selling Price</center> </th>
<th><center>Quantity</center> </th>
</tr>
</thead>
<tbody id = "myNewTableBody" class = "tbody2">
<tr class = "tr2">
</tr>
</tbody>
</table>
</div>
<input type = "submit" value = "save" name = "btnsave" onclick = "myFunction()" style = "position : absolute; top : 550px; left : 20px; font-size: 20px;"/></input>
</body>
<script>
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
var trnode = document.createElement("tr");
for(var i = 0; i < data.length; i++){
var tdnode = document.createElement("td");
var textnode = document.createTextNode(data[i]);
tdnode.appendChild(textnode);
trnode.appendChild(tdnode);
}
document.getElementById("myNewTableBody").appendChild(trnode);
};
function myFunction() {
var rows = document.getElementById("table2")
.getElementsByClassName("tbody2")
[0].getElementsByClassName("tr2").length;
var a = 1;
var b = 1;
for(var i = 0; i < rows; i++){
var x =
document.getElementById("table2").rows[a].cells.item(0).innerHTML
var y =
document.getElementById("table2").rows[a].cells.item(4).innerHTML
var a = a + 1;
var b = b + 1;
alert(x);
alert(y);
}
}
</script>
<html>
<head>
heres the seperate code of the save button that's working
<html>
<head>
<body>
<div class="container">
<table id = "table1">
<thead>
<tr>
<th><center>ID</center> </th>
<th><center>Item Name</center> </th>
<th><center>Category</center> </th>
<th><center>Selling Price</center> </th>
<th><center>Quantity</center> </th>
</tr>
</thead>
<tbody class = "tbody2">
<tr class = "tr2">
<td>1</td>
<td>Cake</td>
<td>Pastry</td>
<td>100</td>
<td>5</td>
</tr>
<tr class = "tr2">
<td>2</td>
<td>Bread</td>
<td>Pastry</td>
<td>5</td>
<td>100</td>
</tr>
</tbody>
</table>
</div>
<input type = "submit" value = "save" name = "btnsave"
onclick = "myFunction()" /></input>
</body>
<script>
function myFunction() {
var rows = document.getElementById("table1")
.getElementsByClassName("tbody2")[0]
.getElementsByClassName("tr2").length;
var a = 1;
var b = 1;
for(var i = 0; i < rows; i++){
var x = document.getElementById("table1").rows[a].cells.item(0).innerHTML
var y = document.getElementById("table1").rows[a].cells.item(4).innerHTML
var a = a + 1;
var b = b + 1;
alert(x);
alert(y);
}
}
</script>
</html>
In this code, second table, table with id table2 is empty. When you take, first column, in it's second row(table body), you get a null. Then you trying to access innerHTML property on a null element. Add some content to table2 and run check it again.
Again same problem comes when you say, document.getElementById("table2").rows[a].cells.item(4).innerHTML. Here you are trying to access 5th cell of a row, which contains only 4 cells.

using jquery on javascript built table

I built an table using JavaScript. However when I try to call jQuery on that table it doesnt work. I am trying to make jQuery highlight the columns of the table when I hoover with it.
Here is my code
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New row')
// Append a text node to the cell
newCell.appendChild(newText);
//Apend new cell to same row
var newCell = newRow.insertCell(1);
var newText = document.createTextNode('Nea')
newCell.appendChild(newText);
//highlight column
$('td').on('mouseenter', function() {
var i = $(this).parent().children().index(this);
$('col').removeClass('hovered');
$('col:nth-child(' + (i + 1) + ')').addClass('hovered');
});
$('td').on('mouseleave', function() {
$('col').removeClass('hovered');
});
table {
border-collapse: collapse;
}
table tr:hover {
background-color: grey;
}
col.hovered {
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
Here is JsFiddle
http://jsfiddle.net/4sR2G/764/
I managed to get the effect using
<colgroup>
<col></col>
<col></col>
<col></col>
</colgroup>
From one of the examples you gave.

Is it possible to find number of td's within table and then apply col width inside table tag by using Javascript?

Is it possible to add "col width" tag according to number of td tags, within Table tag. if there are 2 td's,then it should add 2 "col width". & if there are 3 then, 3 "col width". and so on.
<!DOCTYPE html>
<html>
<head>
<title>HTML colgroup Tag</title>
</head>
<body>
<p>This example shows a colgroup that has three columns of different widths:
</p>
<table border="1">
<tr>
<th>Heading</th>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
<table border="1">
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
</table>
</body>
</html>
Please can anyone help me,to add "col group" tag according to number of td.
Expected Output:-
<!DOCTYPE html>
<html>
<head>
<title>HTML colgroup Tag</title>
</head>
<body>
<p>This example shows a colgroup that has three columns of different widths:
</p>
<table border="1">
<colgroup>
<col width="50%"></col>
<col width="20%"></col>
<col width="30%"></col>
</colgroup>
<tr>
<th>Heading</th>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
</table>
<table border="1">
<colgroup>
<col width="50%"></col>
<col width="50%"></col>
</colgroup>
<tr>
<td>col 1</td>
<td>col 2</td>
</tr>
</table>
</body>
</html>
you need to first loop through the tables and get the td count for each table. and then create a colgroup based on the count of td's
something like this
var output = '';
$('table').each(function() {
var colCount = 0;
$(this).find('tr:nth-child(1) td').each(function() { // Get the count of table columns
if ($(this).attr('colspan')) { // if there is a <td colspan>
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
console.log($(this));
});
var colgroupList = '';
for (i = 0; i < colCount; i++) { // Add a <colgroup></colgroup> for each <td>
colgroupList += '<col width="50%"></col>';
console.log(colgroupList);
}
console.log('<colgroup>' + colgroupList + '</colgroup>');
$(this).find("tbody").prepend('<colgroup>' + colgroupList + '</colgroup>');
output += $(this).html();
});
here's a working JSFIDDLE for the same.
In jQuery you can count the number of tds in the table by:
var count = $('#tableId td').length();
You can add atrributes to a table by doing:
$('#tableId').attr('name', 'value');
jQuery('table').each(function(){
var t = jQuery(this);
var count = t.children('tr').eq(0).find('td').length;
var colgroup = jQuery('<colgroup/>', { 'span': count });
for(var i = 1; i <= count; i++){
colgroup.append('<col/>',{ 'width' : (100/count)+'%' };
}
t.prepend(colgroup);
});
Untested but should be a good starting point
Yes, you can use jQuery to make things easy.
Here is an example (I used the id "table1" in the table):
$(document).ready(function () {
var size = $("#table1 tr:first > td").length;
var tg = '<colgroup span="' + size + '">';
for(x=0; x<size; x++) {
tg += '<col></col>';
}
tg += '</colgroup>';
$(tg).insertBefore('#table1 > tbody > tr:first');
});
Hope it helps.

How can I get the corresponding table column (td) from a table header (th)?

I want to get the entire column of a table header.
For example, I want to select the table header "Address" to hide the address column, and select the "Phone" header to show the correspondent column.
<table>
<thead>
<tr>
<th id="name">Name</th>
<th id="address">Address</th>
<th id="address" class='hidden'>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>Freddy</td>
<td>Nightmare Street</td>
<td class='hidden'>123</td>
</tr>
<tr>
<td>Luis</td>
<td>Lost Street</td>
<td class='hidden'>3456</td>
</tr>
</tbody>
I want to do something like http://www.google.com/finance?q=apl (see the related companies table) (click the "add or remove columns" link)
Something like this would work -
$('th').click(function() {
var index = $(this).index()+1;
$('table td:nth-child(' + index + '),table th:nth-child(' + index + ')').hide()
});
The code above will hide the relevant column if you click on the header, the logic could be changed to suit your requirements though.
Demo - http://jsfiddle.net/LUDWQ/
With a couple simple modifications to your HTML, I'd do something like the following (framework-less JS):
HTML:
<input class="chk" type="checkbox" checked="checked" data-index="0">Name</input>
<input class="chk" type="checkbox" checked="checked" data-index="1">Address</input>
<input class="chk" type="checkbox" checked="checked" data-index="2">Phone</input>
<table id="tbl">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>Freddy</td>
<td>Nightmare Street</td>
<td>123</td>
</tr>
<tr>
<td>Luis</td>
<td>Lost Street</td>
<td>3456</td>
</tr>
</tbody>
Javascript:
var cb = document.getElementsByClassName("chk");
var cbsz = cb.length;
for(var n = 0; n < cbsz ; ++n) {
cb[n].onclick = function(e) {
var idx = e.target.getAttribute("data-index");
toggleColumn(idx);
}
}
function toggleColumn(idx) {
var tbl = document.getElementById("tbl");
var rows = tbl.getElementsByTagName("tr");
var sz = rows.length;
for(var n = 0; n < sz; ++n) {
var el = n == 0 ? rows[n].getElementsByTagName("th")[idx] : rows[n].getElementsByTagName("td")[idx];
el.style.display = el.style.display === "none" ? "table-cell" : "none";
}
}
http://jsfiddle.net/dbrecht/YqUNz/1/
I added the checkboxes as it doesn't make sense to bind the click to the column headers as you won't be able to toggle the visibility, only hide them.
You can do something with CSS, like:
<html>
<head>
<style>
.c1 .c1, .c2 .c2, .c3 .c3{
display:none;
}
</style>
</head>
<body>
<table class="c2 c3">
<thead>
<tr>
<th id="name" class="c1">Name</th>
<th id="address" class="c2">Address</th>
<th id="phone" class="c3">Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td class="c1">Freddy</td>
<td class="c2">Nightmare Street</td>
<td class="c3">123</td>
</tr>
<tr>
<td class="c1">Luis</td>
<td class="c2">Lost Street</td>
<td class="c3">3456</td>
</tr>
</tbody>
</table>
</body>
</html>
To hide a column, you add with Javascript the corresponding class to the table. Here c2 and c3 are hidden.
You could add dynamically the .c1, .c2,... in a style tag, or define a maximum number.
The easiest way to do this would be to add a class to each td that matches the class of the header. When you click the , it checks the class, then hides every td with that class. Since only the s in that column would hide that class, it would effectively hide the column.
<table>
<thead>
<th>Name</th>
<th>Address</th>
</thead>
<tbody>
<tr>
<td class="Name">Joe</td>
<td class="Address">123 Main St.
</tbody>
</table>
And the script something like:
$('th').click( function() {
var col = $(this).html(); // Get the content of the <th>
$('.'+col).hide(); // Hide everything with a class that matches the col value.
});
Something like that, anyway. That's probably more verbose than it needs to be, but it should demonstrate the principle.
Another way would be to simply count how many columns over the in question is, and then loop through each row and hide the td that is also that many columns over. For instance, if you want to hide the Address column and it is column #3 (index 2), then you would loop through each row and hide the third (index 2).
Good luck..
Simulating the Google Finance show/hide columns functionality:
http://jsfiddle.net/b9chris/HvA4s/
$('#edit').click(function() {
var headers = $('#table th').map(function() {
var th = $(this);
return {
text: th.text(),
shown: th.css('display') != 'none'
};
});
var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
$.each(headers, function() {
h.push('<th><input type=checkbox',
(this.shown ? ' checked ' : ' '),
'/> ',
this.text,
'</th>');
});
h.push('</tr></thead></table></div>');
$('body').append(h.join(''));
$('#done').click(function() {
var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
$.each(showHeaders, function(i, show) {
var cssIndex = i + 1;
var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
if (show)
tags.show();
else
tags.hide();
});
$('#tableEditor').remove();
return false;
});
return false;
});
jQuery('thead td').click( function () {
var th_index = jQuery(this).index();
jQuery('#my_table tbody tr').each(
function(index) {
jQuery(this).children('td:eq(' + th_index + ');').each(
function(index) {
// do stuff here
}
);
}
);
});
here's a working fiddle of this behaviour:
http://jsfiddle.net/tycRW/
of course, hiding the column with out hiding the header for it will have some strange results.

Categories