Javascript get id from element and then use it - javascript

Can you help me with this problem? I can't use return x value for my other function. I want when I click on some element, then script load ID of clicked element and then change color of element with this ID.
Is there some better solution for my problem? (in pure JS, not in Jquery)
Thanks.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
<script>
document.addEventListener('click', function(e) {
x=e.target.id;
return x
});
document.getElementById(x).onclick =
function(x) {
if (document.getElementById(x).style.backgroundColor !== 'yellow') {
document.getElementById(x).style.backgroundColor = 'yellow';
}
else {
document.getElementById(x).style.backgroundColor = 'red';
}
};
</script>

Change your code to below.
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
document.addEventListener('click', function(e) {
x=e.target.id;
function() {
var bgColor = document.getElementById(x).style.backgroundColor;
if (bgColor !== 'yellow') {
bgColor = 'yellow';
}
else {
bgColor = 'red';
}
}
});
</script>

Ok i find solution on my problem.
The solution was put all my script in one function and than evrything work.
I learning JS about 1 mount and now I have made one simple LIGHTS OFF game.
Now I nedd some function that check all cells color and alert end of game, but i cant answer a new question because by question is not voted well, and i dont know why.
Here is the example of my code:
document.addEventListener('click', function(e) {
var x = e.target.id
var up = ((Math.floor(x.charAt(0))-1).toString()).concat(x.charAt(1));
var down = ((Math.floor(x.charAt(0))+1).toString()).concat(x.charAt(1));
var left = (x.charAt(0)).concat((Math.floor(x.charAt(1))-1).toString());
var right = (x.charAt(0)).concat((Math.floor(x.charAt(1))+1).toString());
if( document.getElementById(x).style.backgroundColor == ''){document.getElementById(x).style.backgroundColor = 'black';}
else{document.getElementById(x).style.backgroundColor ='';}
if(document.getElementById(up)!=null){
if( document.getElementById(up).style.backgroundColor == ''){document.getElementById(up).style.backgroundColor = 'black';}
else{document.getElementById(up).style.backgroundColor ='';}}
if(document.getElementById(down)!=null){
if( document.getElementById(down).style.backgroundColor == ''){document.getElementById(down).style.backgroundColor = 'black';}
else{document.getElementById(down).style.backgroundColor ='';}}
if(document.getElementById(left)!=null){
if( document.getElementById(left).style.backgroundColor == ''){document.getElementById(left).style.backgroundColor = 'black';}
else{document.getElementById(left).style.backgroundColor ='';}}
if(document.getElementById(right)!=null){
if( document.getElementById(right).style.backgroundColor == ''){document.getElementById(right).style.backgroundColor = 'black';}
else{document.getElementById(right).style.backgroundColor ='';}}
// var all = document.getElementsByTagName("TD");
// var i;
// for (i = 0; i < all.length; i++) {
// all[i].style.backgroundColor!=='yellow';
// alert('a')
// break}
})
td {
padding: 50px;
background-color: yellow;
<table>
<tr>
<td id='11'></td>
<td id='12'></td>
<td id='13'></td>
<td id='14'></td>
<td id='15'></td>
</tr>
<tr>
<td id='21'></td>
<td id='22'></td>
<td id='23'></td>
<td id='24'></td>
<td id='25'></td>
</tr>
<tr>
<td id='31'></td>
<td id='32'></td>
<td id='33'></td>
<td id='34'></td>
<td id='35'></td>
</tr>
<tr>
<td id='41'></td>
<td id='42'></td>
<td id='43'></td>
<td id='44'></td>
<td id='45'></td>
</tr>
<tr>
<td id='51'></td>
<td id='52'></td>
<td id='53'></td>
<td id='54'></td>
<td id='55'></td>
</tr>
</table>

Related

Add columns to a new table row in JQuery

I have the following html:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
<td id=col4">7</td>
</tr>
</tbody>
</table>
I would like to use JQuery to append everything after column 3 (col3) to a new row. Ideally I would end up with something like this:
<table id='myTable'>
<tbody>
<tr>
<td id=col1">12</td>
<td id=col2">55</td>
<td id=col3">142</td>
</tr>
<tr>
<td id=col4">7</td>
</tr>
</tbody>
</table>
Any ideas how this could be achieved? I have tried a few things but haven't been able to get it working.
You could define a generic redistribution function, that takes as argument the desired number of columns, and which just fills up the rows with content from top to bottom, using that number of columns.
It could even be a jQuery plugin:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; border: 2px solid }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
Here is a version with one extra statement that sets the colspan on the very last td element so it occupies the remaining columns in the last row:
$.fn.redistribute = function(maxNumCols) {
if (maxNumCols < 1) return;
$(this).each(function () {
let cells = Array.from($("td", this));
let $tr = $("tr", this);
let rowCount = Math.ceil(cells.length / maxNumCols);
for (let i = 0; i < rowCount; i++) {
let $row = i >= $tr.length ? $("<tr>").appendTo(this) : $tr.eq(i);
$row.append(cells.splice(0, maxNumCols));
}
$("td", this).last().attr("colspan", rowCount * maxNumCols - cells.length + 1);
});
}
// I/O management
function alignTable() {
let cols = +$("input").val(); // Get desired number of columns
$("#myTable").redistribute(cols); // Apply to table
}
// Refresh whenever input changes
$("input").on("input", alignTable);
// Refresh on page load
alignTable();
table { border-collapse: collapse; }
td { border: 1px solid; padding: 4px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Desired number of columns: <input type="number" size="3" value="4" min="1">
<table id='myTable'>
<tbody>
<tr>
<td>12</td>
<td>55</td>
<td>142</td>
<td>7</td>
<td>20</td>
<td>410</td>
<td>99</td>
</tr>
</tbody>
</table>
It sounds like you're still new to jQuery. To give you an idea how to solve your described problem, I have written a solution here. I hope it helps you.
// parameters for splitting
var splitIndex = 3,
splitClass = '.split-columns';
// start the splitting
splitColumnsIntoRows();
function splitColumnsIntoRows() {
var $tables = $(splitClass),
numberTables = $tables.length;
if (numberTables == 0) {
return;
}
for (var i = 0; i < numberTables; i++) {
iterateSplittingRows($($tables[i]).find('tr'));
}
}
function iterateSplittingRows($currentRows) {
var $currentRow,
numberRows = $currentRows.length;
if (numberRows == 0) {
return;
}
for (var i = 0; i < numberRows; i++) {
$currentRow = $($currentRows[i]);
iterateSplittingFields($currentRow, $currentRow.find('th, td'));
}
}
function iterateSplittingFields($currentRow, $currentFields) {
var $newRow,
newRows = [],
childrenLength,
numberFields = $currentFields.length;
if (numberFields == 0) {
return;
}
for (var i = 0; i < numberFields; i++) {
if (i < splitIndex) {
continue;
}
if (i % splitIndex == 0) {
$newRow = $('<tr></tr>');
}
$newRow.append($currentFields[i]);
if (i == numberFields - 1) {
childrenLength = $newRow.children().length;
// fill the row with empty fields if the length does not fit the splitIndex
for (var j = splitIndex; j > childrenLength; j--) {
$newRow.append($('<td></td>'));
}
}
if (
(i >= splitIndex && i % splitIndex == splitIndex - 1)
||
i == numberFields - 1
){
newRows.push($newRow);
}
}
$currentRow.after(newRows);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="split-columns">
<tbody>
<tr>
<td class="col_01">01</td>
<td class="col_02">02</td>
<td class="col_03">03</td>
<td class="col_04">04</td>
<td class="col_05">05</td>
<td class="col_06">06</td>
<td class="col_07">07</td>
<td class="col_08">08</td>
<td class="col_09">09</td>
</tr>
<tr>
<td class="col_10">10</td>
<td class="col_11">11</td>
<td class="col_12">12</td>
<td class="col_13">13</td>
<td class="col_14">14</td>
<td class="col_15">15</td>
<td class="col_16">16</td>
<td class="col_17">17</td>
</tr>
<tr>
<td class="col_19">19</td>
<td class="col_20">20</td>
<td class="col_21">21</td>
<td class="col_22">22</td>
<td class="col_23">23</td>
<td class="col_24">24</td>
<td class="col_25">25</td>
</tr>
</tbody>
</table>

Creating a show/hide button to toggle table column

I made a table that has questions on the left side and answers on the right side. By default these answers are hidden. If the user presses a button, they show up.
I've found this code and modified it quite a bit but what is still missing is a single button that toggles between Show and Hide. I don't like having two separate buttons.
Since I wanted the answers to be hidden at the beginning I called up the function with showHideColumn(1, false);. Is this correct or is there any nicer approach for this? Are there any other things once could do to optimize the code? (I'm new to programming)
Thanks.
<table id='idTable'>
<tr><td> Questions 1</td><td> Answer 1</td></tr>
<tr><td> Questions 2</td><td> Answer 2</td></tr>
<tr><td> Questions 3</td><td> Answer 3</td></tr>
<tr><td> Questions 4</td><td> Answer 4</td></tr>
<tr><td> Questions 5</td><td> Answer 5</td></tr>
</table>
<input type='button' onClick='javascript:showHideColumn(1, true);' value='show'>
<input type='button' onClick='javascript:showHideColumn(1, false);' value='hide'>
<script>
showHideColumn(1, false);
function showHideColumn(colNo, doShow) {
var rows = document.getElementById('idTable').rows;
for (var row = 0; row < rows.length; row++) {
var cols = rows[row].cells;
if (colNo >= 1 && colNo < cols.length) {
cols[colNo].style.display = doShow ? '' : 'none';
}
}
}
</script>
You can use single button and change its text like below using "innerHTML":
<script type="text/javascript">
var button = document.querySelector('#button');
button.addEventListener('click', function (event) {
if (button.innerHTML == "Hide") {
//Add Code to Hide Columns
button.innerHTML = "Show";
} else {
//Add Code to Show Columns
button.innerHTML = "Hide";
}
}
);
</script>
First of all set global var doShow and change the bool value on every click true and false with current button value
if( doShow ){
doShow = false;
e.value = 'show';
}else{
e.value = 'hide';
doShow = true;
}
Remove second button.
<table id='idTable'>
<tr>
<td> Questions 1</td>
<td> Answer 1</td>
</tr>
<tr>
<td> Questions 2</td>
<td> Answer 2</td>
</tr>
<tr>
<td> Questions 3</td>
<td> Answer 3</td>
</tr>
<tr>
<td> Questions 4</td>
<td> Answer 4</td>
</tr>
<tr>
<td> Questions 5</td>
<td> Answer 5</td>
</tr>
</table>
<input type='button' onClick='javascript:showHideColumn(this, 1);' value='show'>
and update your custom function prams like this showHideColumn(this, 1) and this showHideColumn(null, 1)
<script>
showHideColumn(null, 1);
var doShow;
function showHideColumn(e, colNo) {
if (e != null) {
if (doShow) {
doShow = false;
e.value = 'show';
} else {
e.value = 'hide';
doShow = true;
}
}
var rows = document.getElementById('idTable').rows;
for (var row = 0; row < rows.length; row++) {
var cols = rows[row].cells;
if (colNo >= 1 && colNo < cols.length) {
cols[colNo].style.display = doShow ? '' : 'none';
}
}
}
</script>

Calculating items that were entered into an array

I'm trying to find a way to calculate the data that was entered into an array.
The JavaScript
function getInput()
{
var even = [];
var odd = [];
var num = prompt("Enter your number");
if (num % 2 === 0) {
alert("Data entered into array.");
even.push(num);
}
else if (num % 2 == 1) {
alert("Data entered into array.");
odd.push(num)
}
else {
alert("Invalid input.");
}
}
function finished() //This is where the calculations are done. It's accessed by a button in my HTML.
{
var sum = document.getElementById("leftSumOutput").innerHTML = even[];
}
This is the structure for the page. I'm trying to use tables to store the outputs.
The HTML
<!DOCTYPE html>
<html>
<head>
<title>Sample Title</title>
<script type="text/javascript" src="assignmentOne.js"></script>
<link rel="stylesheet" type="text/css" href="assignmentOne.css">
<link rel="icon" href="favicon.png" type="image/x-icon" />
</head>
<body>
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input" onclick="getInput()"><b>Click to input data</b></button><br><br>
<button id="done" onclick="finished()">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="leftSumOutput"></td>
<td id="rightSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="leftAvgOutput"></td>
<td id="rightAvgOutput"></td>
</tr>
</table>
</div>
</body>
</html>
I want to calculate the items within the array. I'm a novice, so I apologize in advance.
EDIT: I forgot to mention that I don't know how to calculate the averages of the fields either. Any help with that would be appreciated. Thanks everyone for your assistance so far!
I think you are little bit confused with scoping of variables.
Here is an example of how it could've been done:
(function(w, d) {
var odds = [], evens = [], button, elSumOdds,elSumEvens, elAvgOdds, elAvgEvens, s
w.addEventListener('load', function() {
button = d.querySelector('button')
elSumOdds = d.querySelector('#sum-odds')
elSumEvens = d.querySelector('#sum-evens')
elAvgOdds = d.querySelector('#avg-odds')
elAvgEvens = d.querySelector('#avg-evens')
button.addEventListener('click', calculate)
})
function calculate() {
var i = prompt('enter number') | 0;
if ((i|0)%2) {
odds.push(i)
s = odds.reduce(function(a,n) { return a+n }, 0)
elSumOdds.innerText = s
elAvgOdds.innerText = s / odds.length
} else {
evens.push(i)
s = evens.reduce(function(a,n) { return a+n }, 0)
elSumEvens.innerText = s
elAvgEvens.innerText = s / evens.length
}
}
})(window, document)
<button > calculate</button>
<table>
<tr><td></td><td>Sum</td><td>Avg</td></tr>
<tr><td>Odds</td><td id='sum-odds'></td><td id='avg-odds'></td></tr>
<tr><td>Evens</td><td id='sum-evens'></td><td id='avg-evens'></td></tr>
</table>
If you need to calculate sum of each element in array you need to write map function. Visit link: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
if you just need to know amount of elements, call: alert(even.length);
Note: #vittore 's structure inspired this change.
(function(d) {
d.getElementById('input').addEventListener('click', getInput);
d.getElementById('done').addEventListener('click', finished);
var elSumOdd = d.getElementById('oddSumOutput');
var elSumEven = d.getElementById('evenSumOutput');
var elAvgOdd = d.getElementById('oddAvgOutput');
var elAvgEven = d.getElementById('evenAvgOutput');
var even = [];
var odd = [];
function getInput() {
var num = prompt("Enter your number") | 0;
if (num % 2 == 0) {
even.push(num);
} else if (num % 2 == 1) {
odd.push(num);
} else {
alert("Invalid input.");
}
finished();
}
function finished() { //This is where the calculations are done. It's accessed by a button in my HTML.
elSumOdd.innerHTML = odd.reduce(function(a, b) {
return a + b;
}, 0);
elSumEven.innerHTML = even.reduce(function(a, b) {
return a + b;
}, 0);
elAvgOdd.innerHTML = elSumOdd.innerHTML / odd.length || 0;
elAvgEven.innerHTML = elSumEven.innerHTML / even.length || 0;
}
})(document);
<div align=center>
<h1>Welcome to Assignment One!</h1>
<label for="input">Click for each time you would like to make an input ==></label>
<button id="input"><b>Click to input data</b>
</button>
<br>
<br>
<button id="done">Click here when done</button>
<!--<h1 id="even">Even</h1>
<h1 id="odd">Odd</h1>
<p id="left"></p>
<p id="right"></p>
<p id="leftResult"></p>
<p id="rightResult"></p>-->
<table>
<tr>
<th></th>
<th>Even</th>
<th>Odd</th>
</tr>
<tr>
<td></td>
<td id="even"></td>
<td id="odd"></td>
</tr>
<tr colspan="2">
<td>Sum</td>
<td id="evenSumOutput"></td>
<td id="oddSumOutput"></td>
</tr>
<tr colspan="2">
<td>Average</td>
<td id="evenAvgOutput"></td>
<td id="oddAvgOutput"></td>
</tr>
</table>
</div>

How do I create turns in a Tic Tac Toe game?

Sorry if this is really obvious. I am pretty new to JavaScript. I have had to create a basic X game . Here is the HTML code.
<table border="1" cellpadding="5">
<tbody>
<tr>
<td id="cell1"></td>
<td id="cell2"></td>
<td id="cell3"></td>
</tr>
<tr>
<td id="cell4"></td>
<td id="cell5"></td>
<td id="cell6"></td>
</tr>
<tr>
<td id="cell7"></td>
<td id="cell8"></td>
<td id="cell9"></td>
</tr>
</tbody>
</table>
I had to write a code so that clicking on any cell, would make an X appear on the cell.
function click() {
if (this.id == "cell1") {
document.getElementById("cell1").innerHTML = "X";
} else if (this.id == "cell2") {
document.getElementById("cell2").innerHTML = "X";
} else if (this.id == "cell3") {
document.getElementById("cell3").innerHTML = "X";
} else if (this.id == "cell4") {
document.getElementById("cell4").innerHTML = "X";
} else if (this.id == "cell5") {
document.getElementById("cell5").innerHTML = "X";
} else if (this.id == "cell6") {
document.getElementById("cell6").innerHTML = "X";
} else if (this.id == "cell7") {
document.getElementById("cell7").innerHTML = "X";
} else if (this.id == "cell8") {
document.getElementById("cell8").innerHTML = "X";
} else if (this.id == "cell9") {
document.getElementById("cell9").innerHTML = "X";
}
}
document.getElementById("cell1").onclick = click;
document.getElementById("cell2").onclick = click;
document.getElementById("cell3").onclick = click;
document.getElementById("cell4").onclick = click;
document.getElementById("cell5").onclick = click;
document.getElementById("cell6").onclick = click;
document.getElementById("cell7").onclick = click;
document.getElementById("cell8").onclick = click;
document.getElementById("cell9").onclick = click;
This method successfully creates an X into each and every cell on the table when clicked. The next task is something I don't understand as I have to now incorporate 'O's into the table, like a Tic Tac Toe Game..which is fine but there should be turns like once there is an X the next one should be an O and then an X and so on. Can anyone tell me please what would be appropriate to do and which method/function can be used in such an instance? Ta!
you need a variable for it
var nextTurn = 'X'
at the top
then something like:
if (this.id == "cell1")
{
if(document.getElementById("cell1").innerHTML == ""){
document.getElementById("cell1").innerHTML = nextTurn;
changeTurn();
}
}
etc
function changeTurn(){
if(nextTurn == 'X'){
nextTurn = 'O';
} else {
nextTurn = 'X';
}
}
I have cleaned up your code a bit:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
<style type="text/css">
td{width:20px;height:20px;text-align: center;vertical-align: middle;}
</style>
</head>
<body>
<table border="1" cellpadding="5">
<tbody>
<tr>
<td ></td>
<td ></td>
<td ></td>
</tr>
<tr>
<td ></td>
<td ></td>
<td ></td>
</tr>
<tr>
<td ></td>
<td ></td>
<td ></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
//IE 8 and below doesn't have String.trim() so have to add it
if(!String.prototype.trim){
String.prototype.trim=function(){
return this.replace(/^[\s]*[\s]*$/igm,"");
}
}
var game={
currentPlayer:"X",
move:function(e){
e=window.event||e;//IE uses window.event
var src=e.target||e.srcElement;
if(src.tagName==="TD"&&src.innerHTML.trim()===""){
src.innerHTML=game.currentPlayer;
game.currentPlayer=(game.currentPlayer==="X")?"O":"X";
}
}
}
var table=document.body.getElementsByTagName("table")[0];
if(typeof table.addEventListener==="function"){
table.addEventListener("click",game.move);
}else if(typeof table.attachEvent){
//for IE
table.attachEvent("onclick", game.move);
}
</script>
</body>
</html>

Pure Javascript: onClick executes toggle rows -- need image swap

First post, long time looker. Stack Overflow ROCKS!
Need some help. I am primarily a Business Intelligence/Data Warehouse professional. I need to use a bit of Javascript to create a collapsing row report in a report writing tool where I cannot anticipate the ability to call JQuery (Internal LAN deployment). Therefore I need pure Javascript.
The premise is I need the report to open with rows only at the Manager/District level but have the ability to open the District clusters to see the assigned Sales Reps and their contribution.
I found code that does this (quite well actually by hiding the repeating District Manager's name) but it uses text objects ("+" and "--") to render the links behind the OnClick event. I really, really, really, really need to have it show alternating images.
I tried simply modifying these two sections but the code to render the image in the first block does not match the code for the second block, this causes the ternary operation to fail and the images to do not alternate as expected.
lnk.innerHTML =(lnk.innerHTML == "+")?"--":"+";
var link ='+';
The code below contains the working code with text for onClick action and below a simple onClick that switches the images. Essentially I need the Folder Icons to be in the first cell of the Manager/District grids. I forced the working collapse code into the main Javascript block just to save space.
Any help, insight, guidance, electric cattle prod shocks (ouch) would be appreciated.
Thanks in advance.
UPDATE: created a CodePen for this to make it easier to see what works right now:
http://codepen.io/anon/pen/yjLvh
Thanks!
<html>
<head>
<style type="text/css">
table { empty-cells: show; }
cell {font-family:'Calibri';font-size:11.0pt;color: #000000;}
TD{font-family: Calibri; font-size: 10.5pt;}
TH{font-family: Calibri; font-size: 10.5pt; }
</style>
</head>
<body>
<SCRIPT type=text/javascript>
var tbl;
var toggleimage=new Array("http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png","http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_closed_folder.png")
function trim(str){
return str.replace(/^\s*|\s*$/g,"");
}
function getParent(el, pTagName) {
if (el == null) return null;
else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // Gecko bug, supposed to be uppercase
return el;
else
return getParent(el.parentNode, pTagName);
}
function toggleSection(lnk){
var td = lnk.parentNode;
var table = getParent(td,'TABLE');
var len = table.rows.length;
var tr = getParent(td, 'tr');
var rowIndex = tr.rowIndex;
var rowHead=table.rows[rowIndex].cells[1].innerHTML;
lnk.innerHTML =(lnk.innerHTML == "+")?"--":"+";
vStyle =(tbl.rows[rowIndex+1].style.display=='none')?'':'none';
for(var i = rowIndex+1; i < len;i++){
if (table.rows[i].cells[1].innerHTML==rowHead){
table.rows[i].style.display= vStyle;
table.rows[i].cells[1].style.visibility="hidden";
}
}
}
function toggleRows(){
tables =document.getElementsByTagName("table");
for(i =0; i<tables.length;i++){
if(tables[i].className.indexOf("expandable") != -1)
tbl =tables[i];
}
if(typeof tbl=='undefined'){
alert("Could not find a table of expandable class");
return;
}
//assume the first row is headings and the first column is empty
var len = tbl.rows.length;
var link ='+';
var rowHead = tbl.rows[1].cells[1].innerHTML;
for (j=1; j<len;j++){
//check the value in each row of column 2
var m = tbl.rows[j].cells[1].innerHTML;
if(m!=rowHead || j==1){
rowHead=m;
tbl.rows[j].cells[0].innerHTML = link;
// tbl.rows[j].cells[0].style.textAlign="center";
tbl.rows[j].style.background = "#FFFFFF";
}
else
tbl.rows[j].style.display = "none";
}
}
var oldEvt = window.onload;
var preload_image_1=new Image()
var preload_image_2=new Image()
preload_image_1.src=toggleimage[0]
preload_image_2.src=toggleimage[1]
var i_image=0
function testloading() {
isloaded=true
}
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
window.onload = function() { if (oldEvt) oldEvt(); toggleRows(); testloading();}
</SCRIPT>
<TABLE class=expandable width="400px" border="1" cellspacing="0" frame="box" rules="all" >
<THEAD>
<TR>
<TH bgColor="#E6E4D4"> </TH>
<TH bgColor="#E6E4D4" align="left">Manager</TH>
<TH bgColor="#E6E4D4" align="left">Sales Rep</TH>
<TH bgColor="#E6E4D4" align="left">Amount </TH></TR>
</THEAD>
<TBODY>
<TR>
<TD> </TD>
<TD>Sarah Jones</TD>
<TD><i>Georgia District Reps</i></TD>
<TD>500000</TD></TR>
<TR>
<TD> </TD>
<TD>Sarah Jones</TD>
<TD>Rex Smtih</TD>
<TD>350000</TD></TR>
<TR>
<TD> </TD>
<TD>Sarah Jones</TD>
<TD>Alex Anderson</TD>
<TD>150000</TD></TR>
<TR>
<TD> </TD>
<TD>William Hobby</TD>
<TD><i>Texas District Reps</i></TD>
<TD>630000</TD></TR>
<TR>
<TD> </TD>
<TD>William Hobby</TD>
<TD>Bill Smith</TD>
<TD>410000</TD></TR>
<TR>
<TD> </TD>
<TD>William Hobby</TD>
<TD>Simon Wilkes</TD>
<TD>220000</TD></TR>
</TBODY></font></TABLE>
<br>
<br>
<img name="togglepicture" src="http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_closed_folder.png" border="0">
</body>
</html>
working demo
<html>
<head>
<style type="text/css">
table { empty-cells: show; }
cell {font-family:'Calibri';font-size:11.0pt;color: #000000;}
TD{font-family: Calibri; font-size: 10.5pt;}
TH{font-family: Calibri; font-size: 10.5pt; }
</style>
</head>
<body>
<SCRIPT type=text/javascript>
var tbl;
var toggleimage=new Array("http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png","http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_closed_folder.png")
var closedImgHTML = "<img name=\"togglepicture\" src=\"http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_closed_folder.png\" border=\"0\" height=\"20\">";
var openImgHTML = "<img name=\"togglepicture\" src=\"http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png\" border=\"0\" height=\"20\">";
function trim(str){
return str.replace(/^\s*|\s*$/g,"");
}
function getParent(el, pTagName) {
if (el == null) return null;
else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // Gecko bug, supposed to be uppercase
return el;
else
return getParent(el.parentNode, pTagName);
}
function toggleSection(lnk){
var td = lnk.parentNode;
var table = getParent(td,'TABLE');
var len = table.rows.length;
var tr = getParent(td, 'tr');
var rowIndex = tr.rowIndex;
var rowHead=table.rows[rowIndex].cells[1].innerHTML;
lnk.innerHTML =(lnk.innerHTML == openImgHTML)?closedImgHTML:openImgHTML;
vStyle =(tbl.rows[rowIndex+1].style.display=='none')?'':'none';
for(var i = rowIndex+1; i < len;i++){
if (table.rows[i].cells[1].innerHTML==rowHead){
table.rows[i].style.display= vStyle;
table.rows[i].cells[1].style.visibility="hidden";
}
}
}
function toggleRows(){
tables =document.getElementsByTagName("table");
for(i =0; i<tables.length;i++){
if(tables[i].className.indexOf("expandable") != -1)
tbl =tables[i];
}
if(typeof tbl=='undefined'){
alert("Could not find a table of expandable class");
return;
}
//assume the first row is headings and the first column is empty
var len = tbl.rows.length;
var link =''+closedImgHTML+'';
var rowHead = tbl.rows[1].cells[1].innerHTML;
for (j=1; j<len;j++){
//check the value in each row of column 2
var m = tbl.rows[j].cells[1].innerHTML;
if(m!=rowHead || j==1){
rowHead=m;
tbl.rows[j].cells[0].innerHTML = link;
// tbl.rows[j].cells[0].style.textAlign="center";
tbl.rows[j].style.background = "#FFFFFF";
}
else
tbl.rows[j].style.display = "none";
}
}
var oldEvt = window.onload;
var preload_image_1=new Image()
var preload_image_2=new Image()
preload_image_1.src=toggleimage[0]
preload_image_2.src=toggleimage[1]
var i_image=0
function testloading() {
isloaded=true
}
function toggle() {
if (isloaded) {
document.togglepicture.src=toggleimage[i_image]
}
i_image++
if (i_image>1) {i_image=0}
}
window.onload = function() { if (oldEvt) oldEvt(); toggleRows(); testloading();}
</SCRIPT>
<TABLE class=expandable width="400px" border="1" cellspacing="0" frame="box" rules="all" >
<THEAD>
<TR>
<TH bgColor="#E6E4D4"> </TH>
<TH bgColor="#E6E4D4" align="left">Manager</TH>
<TH bgColor="#E6E4D4" align="left">Sales Rep</TH>
<TH bgColor="#E6E4D4" align="left">Amount </TH></TR>
</THEAD>
<TBODY>
<TR>
<TD> </TD>
<TD>Sarah Jones</TD>
<TD><i>Georgia District Reps</i></TD>
<TD>500000</TD></TR>
<TR>
<TD> </TD>
<TD>Sarah Jones</TD>
<TD>Rex Smtih</TD>
<TD>350000</TD></TR>
<TR>
<TD> </TD>
<TD>Sarah Jones</TD>
<TD>Alex Anderson</TD>
<TD>150000</TD></TR>
<TR>
<TD> </TD>
<TD>William Hobby</TD>
<TD><i>Texas District Reps</i></TD>
<TD>630000</TD></TR>
<TR>
<TD> </TD>
<TD>William Hobby</TD>
<TD>Bill Smith</TD>
<TD>410000</TD></TR>
<TR>
<TD> </TD>
<TD>William Hobby</TD>
<TD>Simon Wilkes</TD>
<TD>220000</TD></TR>
</TBODY></font></TABLE>
<br>
<br>
</body>
</html>

Categories