Navigate a Table via the keyboard? - javascript

I'm trying to make a table that can do the following.
Row x Cols = 3x3: ok
Navigate via keyboard: ok
When 'focus' (or something) is on a cell update div2 with the data-param2: not working.
When pressing Enter on keyboard, update div1 with data-param1: not working
<html>
<head>
<title>arrows.htm</title>
<script language="javascript" type="text/javascript" src="js/keycode.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script type="text/javascript">
var b4 = "";
var col = 1;
var row = 1;
function bg() {
var rc = "r" + row + "c" + col;
if (b4 == "") b4 = rc;
document.getElementById(b4).style.backgroundColor = "white";
document.getElementById(rc).style.backgroundColor = "yellow";
b4 = rc;
}
function test(){
document.getElementById("q").innerHTML=this.id;
}
function processKeyDown(e) {
var keyCode;
if(e.which) { keyCode = e.which; }
else {
alert("Unknown event type.");
return ;
}
processKeyHandle(keyCode);
}
function processKeyHandle(keyCode) {
var nc = 0;
switch(keyCode) {
case VK_LEFT :
if (col > 1) col--;
bg();
break;
case VK_UP :
if (row > 1) row--;
bg();
break;
case VK_RIGHT :
if (col < 3) col++;
bg();
break;
case VK_DOWN :
if (row < 3) row++;
bg();
case VK_ENTER :
break;
}
}
</script>
</head>
<body onload="bg()" onkeydown="processKeyDown(event);" >
<div id="div1">test</div>
<div id="div2">test2</div>
<div>
<table border="1" id="tab">
<tr>
<td id="r1c1"><img class="imgs" height="100" width="50" class="e" data-param1="666" data-param2="777" src="http://web.scott.k12.va.us/martha2/dmbtest.gif" /></td>
<td id="r1c2">b0</td>
<td id="r1c3">c0</td>
</tr>
<tr>
<td id="r2c1">a1</td>
<td id="r2c2">b1</td>
<td id="r2c3">c1</td>
</tr>
<tr>
<td id="r3c1">a2</td>
<td id="r3c2">b2</td>
<td id="r3c3">c2</td>
</tr>
</table>
</div>
<script>
$(".imgs").click(function(){
var elmThis = $(this);
$("#div1").text(elmThis.data("param1"));
});
</script>
</body>
</html>

I got it to work
<html>
<head>
</head>
<body onload="bg()" onkeydown="processKeyDown(event);" >
<div id="div1">test</div>
<div id="div2">test2</div>
<div>
<table border="1" id="tab">
<tr>
<td id="r1c1" data-param1="r1c1 param1" data-param2="r1c1 param2">a0</td>
<td id="r1c2" data-param1="r1c2 param1" data-param2="r1c2 param2">b0</td>
<td id="r1c3" data-param1="r1c3 param1" data-param2="r1c3 param2">c0</td>
</tr>
<tr>
<td id="r2c1" data-param1="r2c1 param1" data-param2="r2c1 param2">a1</td>
<td id="r2c2" data-param1="r2c2 param1" data-param2="r2c2 param2">b1</td>
<td id="r2c3" data-param1="r2c3 param1" data-param2="r2c3 param2">c1</td>
</tr>
<tr>
<td id="r3c1" data-param1="r3c1 param1" data-param2="r3c1 param2">a2</td>
<td id="r3c2" data-param1="r3c2 param1" data-param2="r3c2 param2">b2</td>
<td id="r3c3" data-param1="r3c3 param1" data-param2="r3c3 param2">c2</td>
</tr>
</table>
</div>
<script language="javascript" type="text/javascript" src="js/keycode.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script type="text/javascript">
var b4 = "";
var col = 1;
var row = 1;
function bg() {
var rc = "r" + row + "c" + col;
if (b4 == "") b4 = rc;
$("#"+b4).css("backgroundColor","white");
$("#div2").text($("#"+rc).css("backgroundColor","yellow").data("param2"));
b4 = rc;
}
function processKeyDown(e) {
var keyCode;
if(e.which) {
keyCode = e.which;
} else {
alert("Unknown event type.");
return ;
}
processKeyHandle(keyCode);
}
function processKeyHandle(keyCode) {
var nc = 0;
switch(keyCode) {
case VK_LEFT :
if (col > 1) col--;
bg();
break;
case VK_UP :
if (row > 1) row--;
bg();
break;
case VK_RIGHT :
if (col < 3) col++;
bg();
break;
case VK_DOWN :
if (row < 3) row++;
bg();
break;
case VK_ENTER :
$("#div1").text($("#"+b4).data("param1"));
break;
}
}
</script>
</body>
</html>

It looks like you're using $.data() not html5 attributes data-yournamehere
If you want to set or access those, do:
$(this).attr('data-param', 'set-the-value-here');
To retrieve it, simply do $(this).attr('data-param');

Related

How to access span tag inside a TD using DOM

How can I access a inside a element on a table and color it?
I tried using childNodes[x] but I'm not sure how to get the span.
<div id="myDiv">
<table>
<tr>
<td>
<span>40 (14)</span>
</td>
</tr>
<tr>
<td>
<span>24 (19)</span>
</td>
</tr>
<tr>
<td>
<span>24</span>
</td>
</tr>
</table>
</div>
(14) should be colored in RED,
(19) should be colored in RED
24 should be unchanged
Check my solution and example running: https://jsfiddle.net/tabvn/bh6y1gc3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<div id="myDiv">
<table>
<tr>
<td>
<span>40 (14)</span>
</td>
</tr>
<tr>
<td>
<span>24 (19)</span>
</td>
</tr>
<tr>
<td>
<span>24</span>
</td>
</tr>
</table>
</div>
<script type="text/javascript">
var nodes = document.querySelectorAll("#myDiv td span");
for(var i = 0; i < nodes.length; ++i){
var node = nodes[i];
var text = node.innerText;
var openIndex = -1;
var closeIndex = -1;
for(var j = 0; j < text.length; ++j){
if(text[j] === "("){
openIndex = j;
}
if(text[j] === ")"){
closeIndex = j;
}
}
var str = "";
if(openIndex > -1 && closeIndex > -1){
for(var j = 0; j < text.length; ++j){
if(j == openIndex){
str += '<span style="color: red;">';
str += text[j];
}else if(j == closeIndex){
str += text[j];
str += "</span>";
}else{
str += text[j];
}
}
node.innerHTML = str;
}
}
</script>
</body>
</html>

Darts game - checking problems in AngularJS

There is the content of my AngularJS (JavaScript ) file:
// define new Angular module
var myApp = angular.module('myApp',[]);
myApp.controller('MyAppController',function($scope){
$scope.player = '';
$scope.players = [];
$scope.totalPoints = [];
$scope.flag = 1;
$scope.myNumberRegex = /[0-9]/;
$scope.last = {};
$scope.score = {};
$scope.winner = 0;
$scope.nextPlayer = '';
$scope.nextRound = false;
var actualPlayer = 0;
var pointsValue,round = 0;
var internalRoundCounter = 1;
var shootsString = '';
$scope.$watch('roundCount',function(value){
console.log('new value',value);
});
$scope.add = function(){
$scope.players.push({name: $scope.player, totalPoints: 0, fields:[]});
$scope.player = '';
};
$scope.checkForm = function() {
var valid = true;
if ($scope.players.length == 0) {
alert('There is no player added!');
valid = false;
}
if ($scope.roundCount < 3 || $scope.roundCount > 10) {
alert('Incorrect round count!');
valid = false;
}
if ($scope.players.length == 1) {
console.log('Tömb hossza: ', $scope.players.length);
alert('One player is not enough!');
valid = false;
}
if (valid) {
$scope.flag = 2;
var startingPlayer = $scope.players[actualPlayer].name;
$scope.nextPlayer = startingPlayer;
}
};
function showResults(){
$scope.flag = 3;
}
// watching changed value
$scope.$watch('last.id',function(newValue){
console.log('last.id changed',newValue);
pointsValue = 0;
//-----------------------------------------------------------
// checking target to calculate earned points
//-----------------------------------------------------------
if (newValue == "Bull") {
pointsValue += 50;
console.log(pointsValue);
}
else if (newValue == "Outer") {
pointsValue += 25;
console.log(pointsValue);
}
else if (['s','d','t'].indexOf(newValue[0]) != -1) {
var multiplier = 1;
if (newValue[0] == 'd')
multiplier = 2;
else if (newValue[0] == 't')
multiplier = 3;
var tmp = newValue.split("").splice(1,2).join("");
pointsValue += (tmp * multiplier);
}
//-----------------------------------------------------------
// while playing darts
if (round < $scope.roundCount) {
if (internalRoundCounter < 4){
shootsString += newValue+' ';
$scope.players[actualPlayer].totalPoints += pointsValue;
internalRoundCounter++;
}
else{
$scope.players[actualPlayer].fields.push({fieldId : round+1, fieldName : shootsString});
shootsString = '';
internalRoundCounter = 1;
actualPlayer++;
if (actualPlayer == $scope.players.length) {
actualPlayer = 0;
round++;
}
$scope.nextPlayer = $scope.players[actualPlayer].name;
}
}
// when game finished
else{
showResults();
$scope.winner = $scope.players[0].name;
// find winner in array
for (var i=1; i<$scope.players.length; i++){
if ($scope.players[i].totalPoints > $scope.players[i-1].totalPoints){
$scope.winner = $scope.players[i].name;
}
}
console.log($scope.players);
}
});
});
myApp.directive('dartClickListener', function() {
return {
restrict: 'A',
scope: false,
link: function(scope,element,attrs) {
console.log(angular.element(element));
angular.element(element).find('g').children().bind('click',function(){
console.log(angular.element(this).attr('id'));
scope.last.id = angular.element(this).attr('id');
scope.$apply();
});
}
}
});
<!DOCTYPE html>
<html ng-app="myApp" ng-init="roundCount=3">
<head lang="en">
<meta charset="UTF-8">
<title>.:: Darts ::.</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="myscript.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="MyAppController">
<div id="start" ng-show="flag == 1">
<div>
<h1 class="stdCell gameTitle">Darts</h1>
</div>
<div>
<table>
<tr>
<td><label class="stdCell" for="playerName">Add player</label></td>
<td><input type="text" id="playerName" ng-model="player"></td>
<td><input type="button" value="Add" ng-click="add()" ng-disabled="!(!!player)"></td>
</tr>
<tr>
<td><label class="stdCell" for="rounds">Rounds (3-10) </label></td>
<td colspan="2"><input type="text" id="rounds" ng-model="roundCount" ng-pattern="myNumberRegex" ng-required="true"></td>
</tr>
</table>
</div>
<div>
<button ng-disabled="!(!!roundCount)" ng-click="checkForm()">Start game</button>
</div>
</div>
<div ng-show="flag == 2">
<div id="gameState">
<div>
<table>
<tr><td class="stdCell borderedCell tableHeader">Player</td><td class="stdCell borderedCell tableHeader">Points</td></tr>
<tr ng-repeat="player in players"><td class="stdCell borderedCell">{{player.name}}</td><td class="stdCell borderedCell">{{player.totalPoints}}</td></tr>
</table>
</div>
<div>
<h2 class="stdCell" ng-model="nextPlayer">{{nextPlayer}} is next</h2>
</div>
</div>
<div id="darts">
<svg id="dartboard" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="630px" height="630px" viewBox="0 0 787 774" enable-background="new 0 0 787 774" xml:space="preserve">
<g id="areas" dart-click-listener="last.id">
<!-- svg file content -->
<div>
<h3 ng-model="winner" ng-repeat="player in players | filter:winner" class="stdCell">The winner: {{winner}} # points: {{player.totalPoints}}</h3>
</div>
<div>
<table>
<tr>
<td class="stdCell borderedCell tableHeader" rowspan="2">Player</td>
<td class="stdCell borderedCell tableHeader" colspan="{{players[0].fields.length}}">Round</td>
<td class="stdCell borderedCell tableHeader totalPointCell" rowspan="2">Total points</td>
</tr>
<tr>
<td class="stdCell borderedCell resultCell" ng-repeat="field in players[0].fields">{{field.fieldId}}</td>
</tr>
<tr ng-repeat="player in players">
<td class="stdCell borderedCell">{{player.name}}</td>
<td class="stdCell borderedCell resultCell" ng-repeat="field in player.fields">{{field.fieldName}}</td>
<td class="stdCell borderedCell resultCell">{{player.totalPoints}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Everything is about a darts game in AngularJS, but I have two problems with it:
1.) After every 3 shoots the player is changed. The shooting is checking in $scope.$watch('last.id' ...) section. My problem is that before changing a player, I must click once more on darts table, because the code is running only after clicking on either field of the table. How can I eliminate it?
2.) The second problem is, that I have to count also shoots, which not hit the table. How can I do it?
The dartboard is an SVG file, inserted into HTML code, the source is from: link.
Thank you very much for answers! :)

How to control highlighted cell with arrow keys

I have HTML table
When I click on it's cell (not header) this cell is highlighted in red. the rest cells in the same row are highlighted in pink color.
I want to control this red cell using arrow keys.
Here is my HTML code:
<html>
<head>
<title>Table Highlight</title>
</head>
<style>
.highlighted{
color: white;
background-color: red;
}
tr.normal td {
color: black;
background-color: white;
}
.highlighted1 {
color: white;
background-color: pink;
}
</style>
<body onLoad="onLoad()" >
<table id="tbl" border="1">
<tr>
<td style="width:70">Id
<td style="width:70">Name
<td style="width:70">Year
<td style="width:70">Task
</tr>
<tr>
<td style="height:20">
<td style="height:20">
<td style="height:20">
<td style="height:20">
</tr>
<tr>
<td style="height:20">
<td style="height:20">
<td style="height:20">
<td style="height:20">
</tr>
<tr>
<td style="height:20">
<td style="height:20">
<td style="height:20">
<td style="height:20">
</tr>
</table>
<script>
tbl = document.getElementById('tbl');
tbl2 = document.getElementById('tbl');
cnt = 0;
function onLoad() {
td = document.getElementsByTagName('td');
for(j=4;j<td.length;j++){
td[j].innerHTML = " ";
td[j].onclick = function(){highlight(this)}
td[j].onkeydown=function(){key_highlight(event)}
}
}
function key_highlight(oo) {
td = document.getElementsByTagName('td');
for(n=1;i<tbl2.rows;n++){
cnt=0;
/*
if(cnt > tbl2[i].cells.length) return;
highlight(tbl2[i]);
}*/
alert();
//if(oo.keyCode==39)
if(cnt>tbl2.rows[n].cells.length) return;
highlight(tbl2[n].cells);
cnt++;
}
}
function highlight(o) {
for (i=0; i<tbl.cells.length; i++){
tbl.cells[i].className="normal";
tbl.cells[i].parentNode.className="normal";
}
o.parentNode.className = (o.className == "highlighted1")?"normal":"highlighted1";;
o.className=(o.className == "highlighted")?"normal":"highlighted";
}
</script>
</body>
You need to check for keycode on keydown event for the document and apply "highlighted" class to respective td.
HTML :
<table id="tbl" border="1">
<tr>
<td style="width:70" class="highlighted">Id</td>
<td style="width:70">Name</td>
<td style="width:70">Year</td>
<td style="width:70">Task</td>
</tr>
<tr>
<td style="height:20"> 1</td>
<td style="height:20"> Bob</td>
<td style="height:20"> 1998</td>
<td style="height:20"> NA</td>
</tr>
<tr>
<td style="height:20">2</td>
<td style="height:20">Maz</td>
<td style="height:20">2000</td>
<td style="height:20">QA</td>
</tr>
<tr>
<td style="height:20">3</td>
<td style="height:20">Mary</td>
<td style="height:20">1999</td>
<td style="height:20">Code</td>
</tr>
</table>
Jquery code:
var active;
$(document).keydown(function(e){
active = $('td.highlighted').removeClass('highlighted');
var x = active.index();
var y = active.closest('tr').index();
if (e.keyCode == 37) {
x--;
}
if (e.keyCode == 38) {
y--;
}
if (e.keyCode == 39) {
x++
}
if (e.keyCode == 40) {
y++
}
active = $('tr').eq(y).find('td').eq(x).addClass('highlighted');
});
Refer to fiddle for live Demo
You have to keep track of cell position (cellX,cellY) both when you click and when you press a key. Add a global keypress handler (document.onkeydown = ) and increment or decrement cellX and cellY according to the keys pressed.
Chech the running fiddle:
http://jsfiddle.net/aehq9c6f/1/
tbl = document.getElementById('tbl');
tbl2 = document.getElementById('tbl');
var cellX=null;
var cellY=null;
document.onkeydown = keyPressed;
cnt = 0;
function onLoad() {
td = document.getElementsByTagName('td');
for(j=4;j<td.length;j++){
td[j].innerHTML = " ";
td[j].onclick = function(){highlight(this)}
td[j].onkeydown=function(){key_highlight(event)}
}
}
function keyPressed(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var KeyVal=getCharDesc(code);
var maxX=4;
var maxY=4;
if(KeyVal=="left") {
if(cellX===null) cellX=maxX;
if(cellY===null) cellY=maxY/2;
cellX--;
if(cellX<0) cellX=maxX-1;
highlight(tbl.rows[cellY].cells[cellX]);
} else if(KeyVal=="right") {
if(cellX===null) cellX=-1;
if(cellY===null) cellY=maxY/2;
cellX++;
if(cellX>maxX-1) cellX=0;
highlight(tbl.rows[cellY].cells[cellX]);
} else if(KeyVal=="up") {
if(cellX===null) cellX=maxX/2;
if(cellY===null) cellY=maxY;
cellY--;
if(cellY<1) cellY=maxY-1; // avoid top row
highlight(tbl.rows[cellY].cells[cellX]);
} else if(KeyVal=="down") {
if(cellX===null) cellX=maxX/2;
if(cellY===null) cellY=0; // avoid top row
cellY++;
if(cellY>maxY-1) cellY=1; // avoid top row
highlight(tbl.rows[cellY].cells[cellX]);
}
}
function getCharDesc(char_code) {
switch(char_code) {
case 37:return "left";
case 38:return "up";
case 39:return "right";
case 40:return "down";
}
}
function highlight(o) {
for (var i = 0, row; row = tbl.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
row.cells[j].className="normal";
row.cells[j].parentNode.className="normal";
if(row.cells[j]===o) {
cellX=j;
cellY=i;
// alert(cellX+", "+cellY);
}
}
}
o.parentNode.className = (o.className == "highlighted1")?"normal":"highlighted1";;
o.className=(o.className == "highlighted")?"normal":"highlighted";
}
The extra tests like
if(cellX===null) ...
are to allow first keypress if nothing is selected (cellX and cellY are null), if you hit left, cursor will start from right, etc.. (window must have focus so first click window to test).
I changed tbl.cells[i] to tbl.rows[i].cells[j] because on my setup (Firefox) table.cells[..] was not defined

Pure Javascript: onClick toggle rows/ image: Firefox/Chrome - works: IE - does not work

Got some great help from Zeb Rawnsley (you rock!) on resolving the preceding question to my current issue.
Working with some code to allow subordinate rows to be hidden via a collapsible link behind an image. This works perfectly fine in Firefox and Chrome but the image does not alternate after the first iteration in IE (IE 8 specifically my company's standard).
The section of interest is here (I think):
var closedImgHTML = "<img name=\"togglepicture\" src=\"http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_closed_folder.png\" border=\"0\" height=\"50\">";
var openImgHTML = "<img name=\"togglepicture\" src=\"http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png\" border=\"0\" height=\"50\">";
and possibly here (but I don't think so):
lnk.innerHTML =(lnk.innerHTML == openImgHTML)?closedImgHTML:openImgHTML;
This CodePen is for the working version (Firefox/Chrome):
http://codepen.io/anon/pen/yjLvh
This is the HTML for the working version:
<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=\"50\">";
var openImgHTML = "<img name=\"togglepicture\" src=\"http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png\" border=\"0\" height=\"50\">";
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>
The prior set of code without the images (using text for open/close) worked fine in all browsers.
Not sure if there is an image syntax issue in IE or something else. It most certainly is focused on the images since, well, it works fine without images.
Here is the CodePen for the version (text based) working in IE (and others).
http://codepen.io/anon/pen/morpF
Here is the HTML for the "ALL" browser version"
<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;
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;
window.onload = function() { if (oldEvt) oldEvt(); toggleRows();}
</SCRIPT>
<TABLE class=expandable width="400px" border="1" cellspacing="0" frame="box" rules="all" >
<THEAD>
<TR>
<TH width="10%" 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 class="cell">
<TD> </TD>
<TD>Sarah Jones</TD>
<TD>&nbsp</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 Jones</TD>
<TD> </TD>
<TD>620000</TD></TR>
<TR>
<TD> </TD>
<TD>William Jones</TD>
<TD>Bill Smith</TD>
<TD>410000</TD></TR>
<TR>
<TD> </TD>
<TD>William Jones</TD>
<TD>Simon Wilkes</TD>
<TD>220000</TD></TR>
</TBODY></font></TABLE></body>
</html>
Thanks!
Different browsers serialize the DOM differently. Running your code in IE10 gives me this:
foo.innerHTML = "<img name=\"togglepicture\" src=\"http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png\" border=\"0\" height=\"50\">";
foo.innerHTML; // <img name="togglepicture" height="50" src="http://www.iconlooker.com/user-content/uploads/wall/thumb/misc._icons_open_folder.png" border="0">
IE rearranged the attributes, so you no longer have the same string.
Instead of getting the HTML inside the link element, get the image itself and look at its src property.

swapping rows using a javascript

I've a multiple number of rows which is generated by a for condition, with 2 icons up and down. On click of up the selected row should move one step up, and on click of down the selected row should move one step down
<html>
<head>
<body>
<form name="myForm">
<table id="mainTable" border="1" width="100%">
<script>
document.write('<tr>')
document.write('<td>')
document.write('row1')
document.write('</td>')
document.write('</tr>')
document.write('<tr>')
document.write('<td>')
document.write('row2')
document.write('</td>')
document.write('</tr>')
document.write('</table>')
document.write('<table>')
document.write('<tr>')
document.write('<td>')
document.write('<input type="button" value=" move UP " onClick="swapRowUp(getRowIndex(this))"</input>')>
document.write('<input type="button" value="move DOWN" onClick="swapRowDown(getRowIndex(this))"</input>')>
document.write('</td>')
document.write('</tr>')
document.write('</table>')
</script>
</table>
</form>
</body>
</head>
</html>
<script>
var mainTable = document.getElementById("mainTable");
function getRowIndex(el)
{
while( (el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr' );
if( el )
alert(el.rowIndex);
return el.rowIndex;
}
function swapRowUp(chosenRow) {
if (chosenRow.rowIndex != 0) {
moveRow(chosenRow, chosenRow.rowIndex-1);
}
}
function swapRowDown(chosenRow) {
if (chosenRow.rowIndex != mainTable.rows.length-1) {
moveRow(chosenRow, chosenRow.rowIndex+1);
}
}
function moveRow(targetRow, newIndex) {
if (newIndex > targetRow.rowIndex) {
newIndex++;
}
var mainTable = document.getElementById('mainTable');
var theCopiedRow = mainTable.insertRow(newIndex);
for (var i=0; i<targetRow.cells.length; i++) {
var oldCell = targetRow.cells[i];
var newCell = document.createElement("TD");
newCell.innerHTML = oldCell.innerHTML;
theCopiedRow.appendChild(newCell);
copyChildNodeValues(targetRow.cells[i], newCell);
}
//delete the old row
mainTable.deleteRow(targetRow.rowIndex);
}
function copyChildNodeValues(sourceNode, targetNode) {
for (var i=0; i < sourceNode.childNodes.length; i++) {
try{
targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
}
catch(e){
}
}
}
</script>
i'm unable to perform the swap operation, i get cellIndex as null
You can use some sensible JavaScript
up.addEventListener("click", function moveRowUp() {
var row = this.parentNode.parentNode,
sibling = row.previousElementSibling,
parent = row.parentNode;
parent.insertBefore(row, sibling);
});
for some sensible HTML
<table>
<tbody>
<tr>
<td> 1 </td>
<td> filler </td>
</tr>
<tr>
<td> 2 </td>
<td> <button id="up">up</button> </td>
</tr>
</tbody>
</table>
Live Example

Categories

Resources