I am having trouble trying to alert the winner, among other things. I also am trying to alert when the user trys to click on a button that has already been pressed, but have no idea what I am doing in that regard either. All help is appreciated. Thank you guys.
<table>
<tr>
<td id="00" onclick="makeMove(0,0)">00</td>
<td id ="01" onclick="makeMove(0,1)">01</td>
<td id ="02" onclick="makeMove(0,2)">02</td>
</tr>
<tr>
<td id ="10" onclick="makeMove(1,0)">10</td>
<td id ="11" onclick="makeMove(1,1)">11</td>
<td id ="12" onclick="makeMove(1,2)">12</td>
</tr>
<tr>
<td id ="20" onclick="makeMove(2,0)">20</td>
<td id ="21" onclick="makeMove(2,1)">21</td>
<td id ="22" onclick="makeMove(2,2)">22</td>
</tr>
</table>
<hr>
<input id="myMoveButton" type="submit">
<script src="java.js"></script>
Javascript:
// -1 means 0's turn
// 1 means X's turn
// AFTER EVERY MOVE
// UNTIL GAME OVER
// THIS NEEDS TO BE FLIPPED
// IF IT WAS 1, now it will be -1 and vice versa
var turn = 1;
// 0 means no move has been made yet
// on that particular square
var grid = [
[0, 0 ,0],
[0, 0 ,0],
[0, 0, 0]
];
function makeMove(row, column) {
if (grid [row][column] == 0) {
grid[row][column] = turn;
var idOfSquareToChange = row +"" + column;
if (turn == 1) {
$("#"+idOfSquareToChange).html('X');
}else {
$("#"+idOfSquareToChange).html('O');
}
// CHECK IF GAME IS OVER
// IF GAME ISN'T OVER
if (turn == 1) {
turn = -1;
}else {
turn = 1;
}
printGrid();
}else {
alert('That square has been chosen');
}
}
function printGrid(){
var board = grid[0][0] + " " + grid [0][1] + " " + grid[0][2];
board += "\n";
board += grid[1][0] + " " + grid [1][1] + " " + grid[1][2];
board += "\n";
board += grid[2][0] + " " + grid [2][1] + " " + grid[2][2];
alert(board);
}
function isGameOver() {
// HERE IS WHERE OUR LOGIC WOULD GO
// TO SEE IF SOMEONE won
}
This is what i came up with:
function isGameOver() {
for (var i = 0; i < grid.length; i++) {
if(grid[i][0] == grid[i][1] && grid[i][0]==grid[i][2] && grid[i][0]!=0){
alert(grid[i][0]+" Wins");
_win=1;
return;
}
}
for (var i = 0; i < grid.length; i++) {
if(grid[0][i] == grid[1][i] && grid[0][i]==grid[2][i] && grid[0][i]!=0){
alert(grid[0][i]+" Wins");
_win=1;
return;
}
}
if(grid[0][0]==grid[1][1] && grid[0][0] == grid[2][2] && grid[0][0]!=0){
alert(grid[0][0]+" Wins");
_win=1;
return;
}
if(grid[0][2]==grid[1][1] && grid[0][2] == grid[2][0] && grid[2][0]!=0){
alert(grid[1][1]+" Wins");
_win=1;
return;
}
}
Working fiddle
This will check whether data in a single column or in a single row or in diagonals should be same. And if a user wins then he can not click on anything else.
By using lodash, you can abstract a bunch of the pieces of this. I went ahead and re-coded it to show you how I'd do it. This will allow you to make the board whatever size you want and allow for up to 4 players.
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/gqqse6cw/18/
Here's all the HTML you need:
<div class="gameboard"></div>
Here's the script:
var game = function( options ){
options = options || [];
var target = options.target || '.gameboard',
size = options.size || [ 3, 3 ],
players = options.players || 2,
toWin = options.toWin || 3,
symbols = [ 'o', 'x', '+', '!' ],
current,
grid,
setup = function ( ) {
$(target).empty();
current = 0;
grid = [];
_.each(_.range(size[0]), function(r) {
var row = $('<div>')
.addClass('row');
grid.push([]),
_.each(_.range(size[1]), function(c) {
grid[r].push(undefined),
row.append(
$('<button>')
.addClass('square open')
.attr('data-pos',r + ',' + c)
.html(' ')
);
})
$(target).append(row );
});
$(target).append(
$('<div>')
.addClass('player')
.append(
$('<span>')
.html('Player')
)
.append(
$('<span>')
.addClass('symbol')
.html(symbols[0])
)
);
$('.square').click( function(){
if (!($(this).hasClass('disabled'))) makeMove(this)
});
},
makeMove = function (btn) {
var btn = $(btn)
.addClass('disabled')
.html(symbols[current]),
pos = btn.attr('data-pos').split(',');
grid[pos[0]][pos[1]] = current;
checkBoard();
},
checkBoard = function () {
var winners = [];
checkArray()
winners = checkArray(grid,winners); // check rows
winners = checkArray(_.zip.apply(_, grid) ,winners,'vert'); // check columns
var diag = [],
diagReverse = [],
i = 0,
di = 0,
map = [],
mapR = [];
_.each(grid, function(g, gk){
_.each(g, function(cell, ck){
di = ck + i;
diag[di] = diag[di] || [];
diagReverse[di] = diagReverse[di] || [];
map[di] = map[di] || [];
mapR[di] = mapR[di] || [];
diag[di].push(grid[gk][ck]);
diagReverse[di].push( grid[ grid.length - gk - 1 ][ ck ]
);
map[di].push([gk,ck]);
mapR[di].push([(grid.length - gk - 1), ck]);
});
i++;
});
winners = checkArray(diag ,winners, map); // check diagonal
winners = checkArray(diagReverse ,winners, mapR); // check reverse diagonal
if ( winners.length > 0 ) playerWin(winners);
current++;
current = current % players;
$(target + ' .symbol')
.html(symbols[current]);
},
checkArray = function (arr,winners,map) {
map = map || 0;
var winner = [],
setRow = [],
count = 0,
cur = -1;
_.each(arr, function(g, key){
count = 0;
_.each(g, function(cell, ckey){
if (cell===undefined || cell !== cur) {
count = 0;
setRow = [];
}
cur = cell;
count++;
if (map) {
if ( map === 'vert'){
setRow.push([ckey,key]);
} else if ( _.isArray(map)) {
setRow.push([map[key][ckey]]);
}
} else {
setRow.push([key,ckey]);
}
if (count >= toWin) winner = winner.concat(setRow);
});
});
if ( winner.length > 0 ) winners = winners.concat(winner);
return winners;
},
playerWin = function (winners) {
$('.gameboard button')
.addClass('disabled');
_.each(winners, function(w){
$('.gameboard button[data-pos="' + w.join() + '"]')
.addClass('win');
});
$(target).append(
$('<div>')
.addClass('winner')
.append(
$('<h1>')
.html('Congratulations, player ' + symbols[current] + '!')
)
.append(
$('<button>')
.addClass('replay')
.html('Play Again?')
)
);
$('.replay').click ( function(){
setup();
});
};
setup();
}
game();
Related
I'm trying to make a Farm Clicker game myself with javascript. In other words, as you click the Add Gold button, the player will have more gold and will be able to buy new animals with the gold he has earned. But in my code I come across the following error: script.js:42 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
at addGold (script.js:42:54)
at HTMLButtonElement. (script.js:11:42)
What is this error caused by? I leave the codes below.
// global variables
const myContent = document.getElementById("content");
var gold = 0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.addEventListener("click", () => addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats * 5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs * 10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows * 15; //120=>15 8=>1
}
addGold(goldToAdd);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold = null) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else {
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
}
function checkGold() {
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", () => buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.dinnerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null) {
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", () => buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id != "itemBar";
myContent.appendChildren(itemBar);
}
switch (animal) {
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement, id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("geen dier gevonden");
}
}
// add elements
// start application
setInterval(passiveGold, 5000);
}
<div id="content"></div>
<!--<script src="script.js"></script> script is referenced right before </body> -->
the element goldCounter is never going to be added to your dom, that's why it says "Cannot set properties of null". At line number 33, in the if statement there is an error.
Replace line 33, this
if (gold = null) {
with
if (gold == 0) {
Hope, it helps!!
The null do not equals to 0, so if the gold contents 0, gold==null will return false and try find the element with goldCounter id (but the easyest way if(!gold))
At the passiveGold function, you do not have to check the animals bigger than 0, because n*0=0, so nothing will happen (it just make your code nicer).
And the buyAnimal function's front: not appendChildren (perhaps you just misspelled it)
I'm following a tutorial on a crossword puzzle but after I trigger the selectLetter() function by pressing a key I'm getting this message when I run it in chrome:
"Uncaught TypeError: Cannot read property 'clueA' of undefined"*
and this message when I run it in firefox developer:
"TypeError: currentLetter.dataset is undefined".*
I tried using typeof in console.log to track the values of currentLetter and currentLetter.dataset but that's just confused me more.
var allLetters;
var currentLetter;
var wordLetters;
var acrossClue;
var downClue;
var typeDirection = "right";
window.onload = init;
function init() {
allLetters = document.querySelectorAll("table#crossword span");
currentLetter = allLetters[0];
var acrossID = currentLetter.dataset.clueA;
var downID = currentLetter.dataset.clueD;
acrossClue = document.getElementById(acrossID);
downClue = document.getElementById(downID);
formatPuzzle(currentLetter);
for (var i = 0; i < allLetters.length; i++) {
allLetters[i].style.cursor = "pointer";
allLetters[i].onmousedown = function(e) {
formatPuzzle(e.target);
}
}
document.onkeydown = selectLetter;
console.log("----init function----\n" + "Current Letter Type: " + typeof currentLetter + " \ncurrentLetter.dataset Type: " + typeof currentLetter.dataset);
}
function formatPuzzle(puzzleLetter) {
currentLetter = puzzleLetter;
for (var i = 0; i < allLetters.length; i++) {
allLetters[i].style.backgroundColor = "";
}
acrossClue.style.color = "";
downClue.style.color = "";
if (currentLetter.dataset.clueA !== undefined) {
acrossClue = document.getElementById(currentLetter.dataset.clueA);
acrossClue.style.color = "blue";
wordLetters = document.querySelectorAll("[data-clue-a=" + currentLetter.dataset.clueA + "]");
for (i = 0; i < wordLetters.length; i++) {
wordLetters[i].style.backgroundColor = "rgb(231,231,255)";
}
}
if (currentLetter.dataset.clueD !== undefined) {
downClue = document.getElementById(currentLetter.dataset.clueD);
downClue.style.color = "red";
wordLetters = document.querySelectorAll("[data-clue-d=" + currentLetter.dataset.clueD + "]");
for (i = 0; i < wordLetters.length; i++) {
wordLetters[i].style.backgroundColor = "rgb(255,231,231)";
}
}
if (typeDirection === "right") {
currentLetter.style.backgroundColor = "rgb(191,191,255)";
} else {
currentLetter.style.backgroundColor = "rgb(255,191,191)";
}
console.log("----formatPuzzle function----\n" + "Current Letter Type: " + typeof currentLetter + " \ncurrentLetter.dataset Type: " + typeof currentLetter.dataset);
}
function selectLetter(e) {
var leftLetter = currentLetter.dataset.left;
var upLetter = currentLetter.dataset.up;
var rightLetter = currentLetter.dataset.right;
var downLetter = currentLetter.dataset.down;
var userKey = e.keyCode;
console.log("----selectLetter function----\n" + "Current Letter Type: " + typeof currentLetter + " \ncurrentLetter.dataset Type: " + typeof currentLetter.dataset + "\n.dataset.up:" + currentLetter.dataset.up + "\nkeycode:" + userKey);
if (userKey === 37) {
formatPuzzle(leftLetter);
} else if (userKey === 38) {
formatPuzzle(upLetter);
} else if (userKey === 39) {
formatPuzzle(rightLetter);
} else if ((userKey === 40) || (userKey === 13)) {
formatPuzzle(downLetter);
} else if ((userKey === 8) || (userKey === 46)) {
currentLetter.textContent = "";
} else if (userKey === 32) {
switchTypeDirection;
} else if (65 <= userKey <= 90) {
currentLetter.textContent = getChar(userKey);
if (typeDirection === "right") {
formatPuzzle(rightLetter);
} else {
formatPuzzle(downLetter);
}
}
e.preventDefault();
}
function switchTypeDirection() {
}
function getChar(keyNum) {
return String.fromCharCode(keyNum);
}
<table id="crossword">
<caption>Today's Crossword</caption>
<tr>
<td><span id="c1_1" data-letter="C" data-right="c1_2" data-left="c1_8" data-down="c2_1" data-up="c11_1" data-clue-a="a1" data-clue-d="d1"></span><sup>1</sup></td>
<td><span id="c1_2" data-letter="A" data-right="c1_3" data-left="c1_1" data-down="c2_2" data-up="c11_2" data-clue-a="a1" data-clue-d="d2"></span><sup>2</sup></td>
<td><span id="c1_3" data-letter="M" data-right="c1_4" data-left="c1_2" data-down="c2_3" data-up="c11_3" data-clue-a="a1" data-clue-d="d3"></span><sup>3</sup></td>
<td><span id="c1_4" data-letter="O" data-right="c1_5" data-left="c1_3" data-down="c2_4" data-up="c10_4" data-clue-a="a1" data-clue-d="d4"></span><sup>4</sup></td>
<td><span id="c1_5" data-letter="M" data-right="c1_6" data-left="c1_4" data-down="c2_5" data-up="c11_5" data-clue-a="a1" data-clue-d="d5"></span><sup>5</sup></td>
<td><span id="c1_6" data-letter="I" data-right="c1_7" data-left="c1_5" data-down="c2_6" data-up="c11_6" data-clue-a="a1" data-clue-d="d6"></span><sup>6</sup></td>
<td><span id="c1_7" data-letter="L" data-right="c1_8" data-left="c1_6" data-down="c2_7" data-up="c11_7" data-clue-a="a1" data-clue-d="d7"></span><sup>7</sup></td>
<td><span id="c1_8" data-letter="E" data-right="c1_1" data-left="c1_7" data-down="c2_8" data-up="c11_8" data-clue-a="a1" data-clue-d="d8"></span><sup>8</sup></td>
<td class="blank"></td>
</tr>
I expect the arrow keys to change the background color rgb(191,191,255) of the cell the arrow key directs to in the puzzle but the code stops running and a type error is printed to the console.
The error implies that currentLetter is assigned a value that is not a DOM element (because every DOM element has a dataset property).
The only places you assign to currentLetter is in init:
currentLetter = allLetters[0];
and formatPuzzle:
currentLetter = puzzleLetter;
allLetters[0] will be a DOM element.
puzzleLetter is the parameter of formatPuzzle, so lets see whether the function is called and passed something that is not a DOM element.
In selectLetter you are calling formatPuzzle multiple times with different arguments, but none of them is a DOM element. E.g. leftLetter is the value of currentLetter.dataset.left.
Maybe you meant to do
var leftLetter = documnent.getElementById(currentLetter.dataset.left);
// etc
?
Make sure you are only passing DOM elements to the function, and avoid global variables as much as possible.
i have a js search in my page that i don't get perfectly how does work because i don't know 100% js and jquery. As far as i think the code takes the input and search match with a link to a database that returns a JSON value depending on what name you put on the link (?name="the-input-name-here"), then, the code parse the json and determinates if the name of the input it's a valid surname and if it is the check if it has a running page, if it has redirects you to that page. If the input is a valid surname but doesn't have a running page it redirects you to "landing-page-yes.html". If the input isn't a valid surname it redirects you to "landing-page-no.html".
I need help to understand how the code does this in order to make a simplify version. How that call to another url database is parsed by the js ? How can i think something similar with a backend and ajax ? I need to understand 100% what this code does and i'm kinda lost.
THANKS !
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="srchid" width="100" onkeypress="submitonenter(document.getElementById('srchid').value, event, this)" />
<input onclick="nameCheck(document.getElementById('srchid').value);" value="CLICK HERE" type="button" style="background-color:#990033; color:#fff;border-style:outset;">
<div id="nameresults"></div>
<script >
<!--
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
} return false;
}
function cursor_wait() {
document.body.style.cursor = 'wait';
}
// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}
function nameCheck(sName) {
sName = trim(sName);
if(sName == ""){
alert("Please enter a name!");
return false;
}
cursor_wait();
routeToNameLookup(sName);
cursor_clear();
}
function $(id){return document.getElementById(id);}
// Get JSONP
function getJSON(url){
var s = document.createElement('script');
s.setAttribute('src',url);
document.getElementsByTagName('head')[0].appendChild(s);
}
function testcb(data){
//alert(data[0]);
}
function loaded(data) {
var name = document.getElementById('srchid').value;
var xmlhttp2;
//Using innerHTML just once to avoid multi reflow
$("nameresults").innerHTML = data[0];
if($("nameresults").innerHTML == 1){
if(data[1] == 1){
//display name page with content
var sNewName = name.replace (/'/g, ""); //remove any '
sNewName = removeSpaces(sNewName);
sNewName = convertNonAscii(sNewName);
//redirect to name crest
var sUrl = "http://www.heraldicjewelry.com/" + sNewName.toLowerCase() + "-crest-page.html";
//getJSON("http://www.gohapp.com/updatenamesearch.php?id=" + data[2] + "&pageurl=" + sUrl + "&callback=testcb");
//postwith(sUrl,{'pname':name});
window.location=sUrl;
} else {
//post to yes page
//postwith("http://www.heraldicjewelry.com/landing-page-yes.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-yes.html";
}
} else {
//post to no page
//postwith("http://www.heraldicjewelry.com/landing-page-no.html",{'pname':name});
window.location="http://www.heraldicjewelry.com/landing-page-no.html";
}
$("nameresults").innerHTML = "";
}
function routeToNameLookup(sSrchName) {
var name = document.getElementById('srchid').value;
if(sSrchName==""){
alert("Please enter your family name.");
} else {
var rn=Math.floor(Math.random()*1000000000000001)
getJSON("http://www.gohapp.com/namesearch_new.php?name="+name+"&rec=1&callback=loaded&rn="+rn);
}
}
function trim (sStr) {
var str = sStr.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
function removeSpaces(string) {
return string.split(' ').join('');
}
var PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
var UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// remove accentued from a string and replace with ascii equivalent
function convertNonAscii(s) {
if (s == null)
return null;
var sb = '';
var n = s.length;
for (var i = 0; i < n; i++) {
var c = s.charAt(i);
var pos = UNICODE.indexOf(c);
if (pos > -1) {
sb += PLAIN_ASCII.charAt(pos);
} else {
sb += c;
}
}
return sb;
}
function submitonenter(name, evt,thisObj) {
evt = (evt) ? evt : ((window.event) ? window.event : "")
if (evt) {
// process event here
if ( evt.keyCode==13 || evt.which==13 ) {
thisObj.blur();
nameCheck(name);
//alert("looking for " + name);
}
}
}
//-->
</script>
Following is the code with an image attached of its output. How can I fix it to show datepicker only once. And only the last calendar should have to be shown which have all the selected dates highlighted on it.
for (var ind = start.getMonth(); ind <= yearDifference; ind++) {
calendarForThisMonth.push(monthNames[ind % 12]);
calendarForThisYear.push(Math.floor(startYear + (ind / 12)));
var showCalendarForThisMonth = calendarForThisMonth.pop();
var showCalendarForThisYear = calendarForThisYear.pop();
saveEachMonthIndex.push(showCalendarForThisMonth);
saveEachYearIndex.push(showCalendarForThisYear);
//console.log(showCalendarForThisMonth);
var line = $('<div class="showInGrid" id="removeMeLater"><span class="dateP" id="calendar' + ind + '" ></span></div>');
//$('#myCalendar').append(line);
var selectedDates={};
for(var eachDateOfMonth in selected) {
if(new Date(selected[eachDateOfMonth]).getMonth() == monthNames[ind%12]) {
selectedDates[new Date(selected[eachDateOfMonth])] = new Date(selected[eachDateOfMonth]);
console.log(selectedDates[new Date(eachDateOfMonth)]);
dateObj.setMonth(showCalendarForThisMonth);
dateObj.setYear(showCalendarForThisYear);
var line = $('<div class="showInGrid" id="removeMeLater"><span class="dateP" id="calendar' + ind + '" ></span></div>');
$('#myCalendar').append(line);
line.find("#calendar" + ind).datepicker({defaultDate:dateObj,
beforeShowDay: function (dateToHighlight) {
var Highlight = selectedDates[dateToHighlight];
if (Highlight) {
return [true, "Highlighted", Highlight];
}
else {
return [true, '', ''];
}
}
});delete dateObj;
}
}
var saveId = $("#calendar"+ind).attr("id");
console.log(saveId);
}
I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.