Validating Empty Squares TicTacToe - Javascript only - javascript

First I would like to say thank you to the individuals that helped me with this question before. For the ones that decided to close my post without even trying to first assist me, please refrain from closing my post if you are not deciding to help and calling my issue too broad. Also, I'm not looking as of this time to "optimize" my code or for corrections with how I expatiate my summary below. Now, for the real issue...
I'm trying my hand at building a tic-tac-toe game with plain vanilla Javascript, so I'm hoping we can stay in the boundaries of keeping it simple Javascript. Do not optimize code!
What I require is the following: I need code that will check each square to see if it's filled with an X or an O. If squares are still available, no need for an alert but if all squares are filled, I need it to alert me "No more moves!"
I have started the function checkEmpty
Thank you for your assistance and time!
Here is the code I have got so far:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Tic Tac Toe</title>
<style>
td {
border: 1px solid black;
height: 250px;
width: 250px;
font-family: sans-serif;
font-size: 150pt;
text-transform: uppercase;
}
</style>
</head>
<body>
<table>
<tr>
<td align="center" id="square1" onclick="displayMarker('square1');"></td>
<td align="center" id="square2" onclick="displayMarker('square2');"></td>
<td align="center" id="square3" onclick="displayMarker('square3');"></td>
</tr>
<tr>
<td align="center" id="square4" onclick="displayMarker('square4');"></td>
<td align="center" id="square5" onclick="displayMarker('square5');"></td>
<td align="center" id="square6" onclick="displayMarker('square6');"></td>
</tr>
<tr>
<td align="center" id="square7" onclick="displayMarker('square7');"></td>
<td align="center" id="square8" onclick="displayMarker('square8');"></td>
<td align="center" id="square9" onclick="displayMarker('square9');"></td>
</tr>
</table>
<script>
var cp1 = 1;
function displayMarker(allSquares) {
if (document.getElementById(allSquares).innerHTML != "") {
alert("Choose another square");
}
else {
if (cp1 == 1) {
document.getElementById(allSquares).innerHTML = "X";
cp1 = 2;
}
else {
document.getElementById(allSquares).innerHTML = "O";
cp1 = 1;
}
}
checkEmpty();
}
function checkEmpty() {
for (var i = 1; i <= 9; i++) {
console.log(document.getElementById('square' + i).innerHTML + " square" + i);
}
</script>
</body>
</html>

Should work:
function checkEmpty() {
for (var i = 1; i <= 9; i++) {
if (!document.getElementById('square' + i).innerHTML) return;
}
alert("all squares filled");
}

function checkEmpty() {
var isEmpty = false;
for (var i = 1; i <= 9; i++) {
var squareVal = document.getElementById('square' + i).innerHTML;
if(squareVal.length == 0)
{
isEmpty = true;
break;
}
}
if(!isEmpty)
{
alert('No more moves');
}
}

Related

jQuery disable click function when value gets to 0

I've been trying many different methods and rewriting my code to achieve something that I feel is quite simple but I can't seem to get it.
I have two increment/decrement buttons but I want to disable the click function on the subtract button when the value reaches 0 as to not input negative numbers.
Currently on my jsfiddle I have the calculator working, however when I try to disable the subtract button when the value is 0, it disables the button completely, even when the value is no longer 0. It seems jQuery is not checking to see if the value has changed.
Any ideas on how can I fix this? Thanks!
Example here:
https://jsfiddle.net/jony000/frupofqe/22/
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
JQuery
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function() {
showers++;
rate.html(showers);
})
minus.click(function() {
showers--;
rate.html(showers);
})
/*if (showers == 0) {
minus.css("pointer-events","none");
} else{
minus.css("pointer-events", "auto");
}*/
You have to check if shower is zero inside the click event listener for the minus element:
minus.click(function() {
rate.html(--showers);
if (showers === 0) {
minus.css("pointer-events", "none");
} else{
minus.css("pointer-events", "auto");
}
});
Check for 0 before you decrement. I believe its more clearly readable to just not decrement it rather than disabling the control, unless you had other logic thats not shown in the demo.
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function(){
showers++;
rate.html(showers);
})
minus.click(function(){
if (showers <= 0)
return;
showers--;
rate.html(showers);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
you just need to move your entire if block at the bottom inside of your functions... or better yet, create a new function and call that one inside the others. Here's an example
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
//This is new
var checkForZero = function() {
if (showers == 0) {
minus.css("pointer-events","none");
} else {
minus.css("pointer-events", "auto");
}
};
plus.click(function(){
showers++;
rate.html(showers);
checkForZero(); //call new function
})
minus.click(function(){
showers--;
rate.html(showers);
checkForZero(); //call new function
})
you can do something like this.
var rateMinus = $(".rate-minus");
var value = 0;
updateRateMinus(); // update on initial load
$(".rate-plus").click(function() {
parseInt($(".shower-rate").text(value + 1));
value = value + 1;
updateRateMinus();
});
$(".rate-minus").click(function() {
parseInt($(".shower-rate").text(value - 1));
value = value - 1;
updateRateMinus();
});
function updateRateMinus() {
if ($(".shower-rate").text() == 0) {
rateMinus.css('pointer-events', 'none');
} else {
rateMinus.css("pointer-events", "auto");
}
}
You could just set up an call that would check a given condition (if your value is 0) and use that to toggle if your subtract button was enabled or disabled via a ternary operation :
minus.css("pointer-events",showers === 0 ? "none" : "auto");
Then you could simply check for that scenario when either of your events occur :
plus.click(function(){
showers++;
UpdateRate();
})
minus.click(function(){
showers--;
UpdateRate();
})
function UpdateRate() {
// This will disable your button if showers is 0
minus.css("pointer-events",showers === 0 ? "none" : "auto");
rate.html(showers);
}
Example
var rateMinus = $(".rate-minus");
var ratePlus = $(".rate-plus");
var rate = $(".shower-rate");
var value = 0;
ratePlus.click(function() {
value++;
UpdateRate();
})
rateMinus.click(function() {
value--;
UpdateRate();
})
function UpdateRate() {
debugger;
// This will disable your button if showers is 0
rateMinus.css("pointer-events", value === 0 ? "none" : "auto");
rate.html(value);
}
table {
margin: auto;
color: #cecece;
}
.shower td {
padding: 10px;
}
.rate-minus,
.rate-plus,
.period-minus,
.period-plus {
width: 50px;
height: 50px;
background: #a8d6ff;
border-radius: 100%;
text-align: center;
font-size: 24px;
color: black;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How often do you shower?
<table class="shower">
<tbody>
<tr>
<td class="rate-minus" id="test">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a
</p>
<table class="shower">
<tbody>
<tr>
<td class="period-minus">
-
</td>
<td class="shower-period">
Day
</td>
<td class="period-plus">
+
</td>
</tr>
</tbody>
</table>

Randomly Generate Numbers and Check Matching numbers

I am still new to javascript and HTML. My task is to generate 2 random integer values from 1 to 3. Upon pressing the "Match!" button, an alert box informs the user if the two numbers are the same or not the same. Not sure why my code isn't working. Any help is appreciated.
Demo: https://jsfiddle.net/1rp5xvte/5/#&togetherjs=pJcEH56yoK
$(document).ready(function(){
function myFunction()
{
document.getElementById("generatedNum").innerHTML = Math.random();
{
if (generateNum1 == generateNum2) {
alert ("Both numbers are the same");
}
else {
alert("Both numbers are different");
}
displayGeneratedNum ();
}
}
});
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab Report</title>
<script src="jquery.js"></script>
<script src="myScript.js"></script>
<style>
body{font-size:40px;
text-align:center;
background-color: antiquewhite;}
table {margin-top:100px;
background-color:white;}
td { width:150px;}
span {font-size:40px;}
#correctScore{
background-color:green;
}
#wrongScore{
background-color:red;
}
#missedScore{
background-color:blueviolet;
}
.numberStyle {
padding: 10px 10px 10px 10px;
color:blue;
}
.numberStyle span {
font-size:100px;
}
</style>
</head>
<body>
<table width="800" border="1" align="center">
<tr>
<td id="generatedNum" colspan="6" align="left"><span>Random Numbers
generated : 1</span></td>
</tr>
<tr>
<td colspan="3" align="center">Number 1</td>
<td colspan="3" align="center">Number 2</td>
</tr>
<tr>
<td colspan="3" id="number1" class="numberStyle"><span>1</span></td>
<td colspan="3" id="number2" class="numberStyle"><span>2</span></td>
</tr>
<tr height="50px";>
<td colspan="6"><input type="button" value="MATCH!" style="font-size:50px;">
</input></td>
</tr>
<tr>
<td>Correct:</td>
<td id="correctScore"><span>0<span></td>
<td><span>Wrong<span></td>
<td id="wrongScore"><span>0<span></td>
<td><span>Missed<span></td>
<td id="missedScore"><span>0<span></td>
</tr>
</table>
</body>
</html>
try this code
<html><body><label id='lbl'></label><button id="btn">Match!</button><script src="https://code.jquery.com/jquery-2.2.1.min.js"></script><script>
function randomNumber(a,b)
{
if(b == undefined) {
b = a - 1;
a = 0;
}
var delta = b - a + 1;
return Math.floor(Math.random()*delta) + a
}
$(document).ready(function(){
$('#btn').click(function()
{
var generateNum1 = randomNumber(1,3);
var generateNum2 = randomNumber(1,3);
if (generateNum1 == generateNum2) {
alert ("Both numbers are the same");
}
else {
alert("Both numbers are different");
}
$('#lbl').html(generateNum1 + ";" + generateNum2);
})
});
</script></body></html>
You need a function that generated a random integer within a range.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
button.addEventListener('click', function() {
var num1 = getRandomInt(1, 3);
var num2 = getRandomInt(1, 3);
alert(num1 === num2 ? 'Both numbers are the same' : 'Both numbers are different');
});
JSFiddle Demo: https://jsfiddle.net/1rp5xvte/1/

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>

JavaScript - Traversing the HTML DOM using childNodes causes errors in Non IE browsers

I have the following table being rendered in my browser. It's generated from the server side.
<table id="tblQuestions" class="tblQuestionsContainer" border="0">
<tr>
<td id="1" class="tdQuestion">Are u an indian citizen ?</td>
</tr><tr>
<td><table id="answer-1" border="0">
<tr>
<td><input id="answer-1_0" type="radio" name="answer-1" value="1" /><label for="answer-1_0">Yes</label></td><td><input id="answer-1_1" type="radio" name="answer-1" value="0" /><label for="answer-1_1">No</label></td>
</tr>
</table></td>
</tr><tr>
<td id="2" class="tdQuestion">Do you have a passport ?</td>
</tr><tr>
<td><table id="answer-2" border="0">
<tr>
<td><input id="answer-2_0" type="radio" name="answer-2" value="1" /><label for="answer-2_0">Yes</label></td><td><input id="answer-2_1" type="radio" name="answer-2" value="0" /><label for="answer-2_1">No</label></td>
</tr>
</table></td>
</tr>
</table>
Now I am using the following code in my JavaScript to validate the radio button's checked state.
var tblQuestionBoard=document.getElementById("tblQuestions");
tblAnswer = tblQuestionBoard.rows[1].childNodes[0].childNodes[0]
Now tblAnswer should be an object having the Table with id "answer-1"
In IE, I am getting it. But in Mozilla and rest of the browsers I am getting it as undefined.
How to solve this?
It's because you're using childNodes and whitespaces in the DOM are considered to be text nodes by Firefox et. al but not IE
See this answer for an explanation
My suggestions
1.Set up some wrapper functions that ignore any nodeType other than 1 (ELEMENT_NODE) to do DOM traversing. Something like
function child(elem, index) {
// if index is not supplied, default is 1
// you might be more comfortable making this 0-based
// in which case change i initial assignment value to 0 too
index = index || 1;
// get first child element node of elem
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
// use the index to move to nth-child element node
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
and use like so - Working Demo - (Code at the bottom of the answer for reference)
<table id="myTable">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
<script type="text/javascript">
child(document.getElementById('myTable'), 2); // will get the tbody
</script>
2.Use getElementbyId(), getElementsByTagName() or getElementsByName() instead of relying on position in the DOM
3.Use a JavaScript library that abstracts away browser differences (jQuery comes highly recommended)
The Demo Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)? child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)? child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
<title>DOM Traversal</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
font-family: Verdana, Helvetica, Arial;
font-size: 0.8em;
}
h2 {
text-align:center;
}
table {
border: 1px solid #000;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 2px;
}
fieldset {
border: 0;
}
label {
display: block;
width: 120px;
text-align: right;
float: left;
padding-right: 10px;
margin: 5px 0;
}
input {
margin: 5px 0;
}
input.text {
padding: 0 0 0 3px;
width: 172px;
}
input.button {
margin: 15px 0 0 130px;
}
span {
font-weight: bold;
color: #b7b7b7;
}
</style>
</head>
<body>
<h2>Example to demonstrate use of JavaScript DOM traversing wrapper functions</h2>
<div style="margin: 0 auto; width: 600px;">
<fieldset>
<label for="row">Row Number:</label><input id="row" class="text" type="text" /><br/>
<label for="column">Column Number:</label><input id="column" class="text" type="text" /><br/>
<input id="getCellContents" type="button" class="button" value="Get Cell Contents" />
</fieldset>
<p>Results: <span id="results"></span></p>
<table id="table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Banana</td>
<td>Apple</td>
<td>Orange</td>
<td>Pineapple</td>
<td>Cranberry</td>
</tr>
<tr>
<td>Monkey</td>
<td>Giraffe</td>
<td>Elephant</td>
<td>Tiger</td>
<td>Snake</td>
</tr>
<tr>
<td>C#</td>
<td>Java</td>
<td>Python</td>
<td>Ruby</td>
<td>Haskell</td>
</tr>
<tr>
<td>France</td>
<td>Spain</td>
<td>Italy</td>
<td>Germany</td>
<td>Netherlands</td>
</tr>
</tbody>
</table>
<p style="font-weight:bold;">The Code:
<pre><code>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
if(elem)
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)?
child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)?
child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
</code>
</pre>
</p>
</div>
</body>
</html>

Categories