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

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>

Related

Javascript get id from element and then use it

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>

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>

Validating Empty Squares TicTacToe - Javascript only

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');
}
}

Jquery validation

I am new In jquery created validation and calculation using formula.I have created six input fields.created validation all fields.but when empty all fields click calculation red star symbol showing first two fields not showing remain four fields please help me friends
here my 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">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1'
class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" />
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
calculation all working good.when leave fields empty click calculation show red star required first two column remain not showing help me friends
There is a mistake in the condition you have written for the valueC,valueD, valueE and valueF. You should continue as of valueA and valueA for the remaining too, if you want to achieve the functionality as you are trying to.
But, My Suggestion is to Use http://jqueryvalidation.org/ Plugin for validating the elements. It is very handy to use and customize as required.
Thank you
Check you conditions. small logical mistakes in your conditions. for eg.
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
This will check if either valuec or valued is empty. You are not checking for both empty. You need to add something like this
if (!valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
Brother its not a good trick to make your code lengthy. You could achieve your goal by using each function. Below is an example of doing that. Please have a look.
function validate(){
var formValidate = true;
jQuery(form + " select," + form + " input").each(
function (index) {
var input = jQuery(this);
if (input.val() == "" ) {
input.addClass("error");
input.parent().next("td").fadeIn("slow");
}
else {
input.removeClass("error");
input.parent().next("td").fadeOut("slow");
}
if (input.hasClass('error')) {
if (formValidate == true) {
formValidate = false;
}
}
}
);
if (formValidate == true) {
return true;
}
else {
return false;
}
}
exact solution to your answer is below please copy n paste then check.
<!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>
<title></title>
<script src="../jQuery/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function calculate() {
var answer = 0;
if (validate()) {
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA && valueB && valueC && valueD && valueE && valueF) {
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC)) + (parseFloat(valueF / valueE))) / 3;
}
else {
if (valueA && valueB && valueC && valueD)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueD / valueC))) / 2;
else {
if (valueA && valueB && valueE && valueF)
answer = ((parseFloat(valueB / valueA)) + (parseFloat(valueF / valueE))) / 2;
else (valueA && valueB)
answer = ((parseFloat(valueB / valueA)));
}
}
if (parseFloat(answer) > .0238)
alert("Your Effective Rate = " + parseFloat(answer * 100).toFixed(2));
else if (answer == 0)
alert("Your Effective Rate:0.00% ");
else
alert("Oops, something has gone terribly wrong!Please attach at least 2 months of your most recent credit card processing statements and one of our specialists will respond within 24 hours with an accurate cost analysis");
}
return false;
}
function validate() {
var status = false;
var valueA = $("#valuea").val()
var valueB = $("#valueb").val()
var valueC = $("#valuec").val()
var valueD = $("#valued").val()
var valueE = $("#valuee").val()
var valueF = $("#valuef").val()
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
status = true;
$("#spanb").hide();
}
else {
status = false;
$("#spanb").show();
}
if (valueC && !valueD) {
status = false;
$("#spand").show();
$("#spanc").hide();
}
if (!valueC && valueD) {
status = false;
$("#spanc").show();
$("#spand").hide();
}
if (valueE && !valueF) {
status = false;
$("#spanf").show();
$("#spane").hide();
}
if (!valueE && valueF) {
status = false;
$("#spane").show();
$("#spanf").hide();
}
if (valueC && valueD) {
$("#spand").hide();
$("#spanc").hide();
return true;
}
if (valueE && valueF) {
status = true;
$("#spane").hide();
$("#spanf").hide();
}
//change is here
//change status value as per your requirement
if (!valueC && !valueD) {
//status = false;
$("#spand").show();
$("#spanc").show();
}
if (!valueE && !valueF) {
//status = false;
$("#spanf").show();
$("#spane").show();
}
return status;
}
</script>
</head>
<body>
<form>
<table class="calculator" border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading">
<td colspan="3" align="center">
Whats your effective rate?
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 1</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuea' id="valuea" onkeypress="return isNumber(event)"
autocomplete="off" /></td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spana">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valueb' id="valueb" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanb">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 2</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuec' id="valuec" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanc">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valued' id="valued" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spand">*</span>
</td>
</tr>
<tr class="monthheading">
<td colspan="2">
<strong>Month 3</strong>
</td>
</tr>
<tr class="calcrow">
<td>
Total Sales, Including Amex
</td>
<td align="center">
<input type='text' name='valuee' id="valuee" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spane">*</span>
</td>
</tr>
<tr class="calcrow2">
<td>
Total Fees, less any terminal or rental fees
</td>
<td align="center">
<input type='text' name='valuef' id="valuef" onkeypress="return isNumber(event)"
autocomplete="off" />
</td>
<td align="center">
<span style="color: Red; font-weight: bold; display: none;" id="spanf">*</span>
</td>
</tr>
<tr class="submit">
<td colspan="3" align="center">
<input type='submit' value='Calculate' onclick="return calculate();" />
</td>
</tr>
<tr class="calcrow">
<td colspan="3" align="center">
</td>
</tr>
</table>
</form>
</body>
</html>
If you really want to do it in that way consider below validation method.
I assume what you want is to check the input fields are empty or not. what you have done is still unclear to me.
To do a proper validation you need to identify and state what should be checked and how should they handled as well.
function validate() {
var status = false;
var valueA = $("#valuea").val();
var valueB = $("#valueb").val();
var valueC = $("#valuec").val();
var valueD = $("#valued").val();
var valueE = $("#valuee").val();
var valueF = $("#valuef").val();
if (valueA) {
$("#spana").hide();
status = true;
}
else {
$("#spana").show();
status = false;
}
if (valueB) {
$("#spanb").hide();
status = true;
}
else {
$("#spanb").show();
status = false;
}
if (valueC) {
$("#spanc").hide();
status = true;
}
else {
$("#spanc").show();
status = false;
}
if (valueD) {
$("#spand").hide();
status = true;
}
else {
$("#spand").show();
status = false;
}
if (valueE) {
$("#spane").hide();
status = true;
}
else {
$("#spane").show();
status = false;
}
if (valueF) {
$("#spanf").hide();
status = true;
}
else {
$("#spanf").show();
status = false;
}
return status;
}

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