Hiding/Showing Div Elements - javascript

This should cycle through the <div> tags, but it isn't even showing the first one. It should show a "0", then 50ms later, show "1", then "2", and then "3". I get nothing.
Here's the HTML:
<div class="header" id="animation">
<div id="aniObj0" style="display: none;" onLoad="runAnimation();">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
The JavaScript:
var aniNum = 0;
var animationDelay = 50;
var frameDelay = 50;
function runAnimation()
{
Console.log("runningAnimation");
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if(aniObj != null){
if(prevObj != null){
aniObj.style.display = 'none;';
}
aniObj.style.display = 'block;';
aniNum++;
if(aniNum == 0){
setTimeout("runAnimation();", animationDelay);
}else{
setTimeout("runAnimation();", frameDelay);
}
}else{
aniNum = 0;
newAnimation();
}
}

You're very close. See code below (and comments in code).
HTML:
<div class="header" id="animation">
<!-- Removed onload="runAnimation()" - onload doesn't exist for a div -->
<div id="aniObj0" style="display: none;">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
JavaScript:
var aniNum = 0;
var animationDelay = 500; //Changed to 500ms to you could see better
var frameDelay = 500; //Changed to 500ms to you could see better
function runAnimation()
{
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if (aniObj != null) {
if (prevObj != null) {
aniObj.style.display = 'none;';
}
aniObj.style.display = '';
aniNum++;
if (aniNum == 0) {
//Changed setTimeout("runAnimation()", animationDelay); to
//setTimeout(runAnimation, animationDelay);
setTimeout(runAnimation, animationDelay);
} else {
setTimeout(runAnimation, frameDelay);
}
} else {
aniNum = 0;
newAnimation();
}
}
//You need to place this in a valid event. onload event of the body maybe?
runAnimation();
Here's a working fiddle.

Related

How to save multiple user inputs into new variables

Im creating a guessing game and the user has 5 attempts to make the correct guess. I want to save their previous guesses (inputs) to show it to them. I have been using the snippet below to save one attempt when the user types into an <input> field, but how can I save the next 4 attempts in new variables such as userGuess2, userGuess3, etc.
var userGuess = document.getElementById("inputField").value;
$('#previousGuesses').text(userGuess);
Ok then let's pretend this is your input
<input type="text" id="inputField">
You can create an index that will increment everytime the users presses enter to save another answer
var i=1;
And the id name your autogenerated spans will have
var name = "previousGuesses";
Now on your function you will save the value when the user presses enter like you described and when that happens it will create a new span element where it will display the value stored
function myFunction(){
$("#inputField").keypress(function( event ) {
if ( event.which == 13 || event.which == 9) {
var userGuess = document.getElementById("inputField").value;//get value of the answer
var span = document.createElement('SPAN');//create a new span
span.innerHTML = userGuess + "<br>";//answer value goes here
span.id = name+i;//this is the id of your new span, remember ids are unique so we attach var i to the name var we declared before
document.body.appendChild(span);
//$('#previousGuesses'+i).text(userGuess);
i++;
}
});
}
now call your function
myFunction();
https://jsfiddle.net/kenpy/m16bojhg/4/
You can just simply add an element for the user's last attempts and add to it.
f(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessSubmit = document.querySelector('.guessSubmit');
var guessField = document.querySelector('.guessField');
var guessCount = 1;
var resetButton;
guessField.focus();
function checkGuess() {
var userGuess = Number(guessField.value);
if(guessCount === 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if(userGuess === randomNumber) {
lastResult.textContent = "Good job! You win!";
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if(guessCount === 10) {
lastResult.textContent = 'Hahaha You suck!';
lowOrHi.textContent = '';
setGameOver();
} else {
lastResult.textContent = "Oops! You're Wrong!";
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
console.log('cheat is: ' + randomNumber);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Play Again?';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for(var i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
body{
background-image: linear-gradient(to left top, #c6fced, #a3efda, #7fe3c7, #54d5b3, #00c89f);
color: #2F3139;
margin: 10rem auto;
height:50vh;
}
h1 {
font-size: 1.5rem;
}
.lastResult {
color: white;
padding: 3px;
}
button {
margin-left:3rem ;
}
<h3 class="display-4 text-center text-muted text-capitalize"></h3>
<div class="container">
<div class="row">
<div class="col-md-6 ">
<h1 class="text-muted text-capitalize">
<span class="text-primary">JavaScript</span> Number guessing game</h1>
<p class="lead">Simply enter a number between 1 - 100 then click the button</p>
</div>
<div class="col-md-6">
<div class="mt-4 d-inline-block">
<div class="form">
<label for="guessField">Guess a number : </label><input type="text" id="guessField" class="guessField">
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas text-center lead">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</div>
</div> </div>
</div>
Resource
JavaScript number guessing game

onclick: picture does not change

My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>

How can I compare numbers in an object against text in the dom?

I have a function that picks a random number from 1 - 6 and then appends it to the DOM. I am trying to compare that number to numbers that are currently in a div in the DOM. So I stored those numbers in a var called cards. When I console.log() the var it returns an array. I converted that array to a string and then I retrieved the text. What is the best way to go about comparing the numbers? Should I do a for loop and if any of those numbers match one of the random numbers drawn take some action? Can some one show me an example of doing this? My code is below.
$(function(){
function dice1(){
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions').text(randomNumber);
return randomNumber;
}
function dice2(){
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions2').text(randomNumber);
return randomNumber;
}
$('#dice1').click(function() {
dice1();
var cards = $('#cards div');
var single = cards.toString();
console.log(cards.text());
if ($('#instructions').text() == cards.text()) {
console.log('match');
}
});
$('#dice2').click(function(){
dice2();
});
});
<section id="container">
<div id="cards">
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
<div id="5">5</div>
<div id="6">6</div>
<div id="7">7</div>
<div id="8">8</div>
<div id="9">9</div>
</div>
<section>
<button id="dice1">Roll dice1</button>
<button id="dice2">Roll dice2</button>
<div id="instructions"></div>
<div id="instructions2"></div>
</section>
</section>
Why not store the cards directly in an array like this:
var cards = [1,2,3,4,5,6,7,8,9];
Then do the comparison like this:
var number = parseInt($("#instructions").text());
if(cards.indexOf(number) >= 0)
console.log("Number found");
else
console.log("Number not found");
If you really want to do it your way, you can do this:
$(".cards div").each(function(){
var number = parseInt($("#instructions").text());
var card = parseInt($(this).text());
if(card == number)
console.log("Number found");
});
Well you could indeed do it with a for loop:
$('#dice1').click(function() {
var random_number = dice1();
var cards = $('#cards div');
for(var i = 0; i < cards.length; i++ ) {
if($(this).html() == random_number) {
alert('Do something!');
}
}
console.log(cards.text());
if ($('#instructions').text() == cards.text()) {
console.log('match');
}
});
But you could also directly match to the ID you've set:
$('#dice1').click(function() {
var random_number = dice1();
var card = $('#cards div[id='+random_number+']');
if(card.length > 0) {
alert('Do something!');
}
});
Remember though, that the ID attribute can not start with a number, so I would create my own attribute here:
<div id="cards">
<div data-number="1">1</div>
<div data-number="2">2</div>
<div data-number="3">3</div>
<div data-number="4">4</div>
<div data-number="5">5</div>
<div data-number="6">6</div>
<div data-number="7">7</div>
<div data-number="8">8</div>
<div data-number="9">9</div>
</div>
And then use jQuery like so:
$('#dice1').click(function() {
var random_number = dice1();
var card = $('#cards div[data-number='+random_number+']');
if(card.length > 0) {
alert('Do something!');
}
});
You can do something like this:
New JS:
$(function () {
function dice1() {
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions').text(randomNumber);
return randomNumber;
}
function dice2() {
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions2').text(randomNumber);
return randomNumber;
}
$('#dice1').click(function () {
var num1 = dice1();
$('#cards div').each(function (index,item) {
if ($(item).text() == num1) {
$(item).css("color", "red");
}
});
$('#dice2').click(function () {
dice2();
});
});
});
Fiddle example
I just learned a way of doing it that solves it dynamically and personally I think it's easier to follow.
<div data-hook="cards" id="cards">
<div data-value="1" id="1">1</div>
<div data-value="2" id="2">2</div>
<div data-value="3" id="3">3</div>
<div data-value="4" id="4">4</div>
<div data-value="5" id="5">5</div>
<div data-value="6" id="6">6</div>
<div data-value="7" id="7">7</div>
<div data-value="8" id="8">8</div>
<div data-value="9" id="9">9</div>
</div>
$(function(){
function dice1(){
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions').text(randomNumber);
return randomNumber;
}
$('#dice1').click(function() {
dice1();
$('[data-hook=cards] [data-value]').find('#instructions'); //'data-hook=cards] [data-value]' selects the element by attr'
var rolledNum = $('#instructions').text(),
selector = '[data-value=' + rolledNum + ']',
$card = $('[data-hook=cards]').find(selector);
//Instead of using an $.each or for loop to compare two numbers I am taking the random number and finding it on the div and then modifying the div.
console.log($card);
$card.css({'opacity':.2});
});
});

Property within an array not being read by a function - Cannot read property of undefined

I am having some trouble. I am working within Business Catalyst which stores dynamic user-submitted data and allows me to output it in whatever way I need.
I have created a series of Web Apps that work together to allow users to take quizzes. Currently I am receiving an error message 'Uncaught TypeError: Cannot read property 'questionText' of undefined'
How my code is working currently:
A user submits a form with quiz/survey data.
They are directed to a new page that runs a search for the most recent quiz/survey submission unique to their user.
The data is output on the page within a div.
A function reads the data and builds the page content accordingly to display the correct quiz/survey results.
The data that is submitted is output in the following format. Note that the {tags} are Business Catalysts way of outputting dynamic information - the {tag} is replaced with the user-submitted data on the page. Also note that I have only shown the data for 3 questions, there are up to 15 in total.
var quizSurvey = "{tag_quiz/survey}";
var w = window.innerWidth;
function Question(questionNumber, questionText, answerType, answerA, answerB, answerC, answerD, correctAnswer, userMultichoice, userTF, userSRating, userSSAnswer, qPassFail) {
this.questionNumber = questionNumber;
this.questionText = questionText;
this.answerType = answerType;
this.answerA = answerA;
this.answerB = answerB;
this.answerC = answerC;
this.answerD = answerD;
this.correctAnswer = correctAnswer;
this.userMultichoice = userMultichoice;
this.userTF = userTF;
this.userSRating = userSRating;
this.userSSAnswer = userSSAnswer;
this.qPassFail = qPassFail;
};
var question = new Array();
question[1] = new Question("1", "{tag_q1-question}", "{tag_q1-answer-type}", "{tag_q1-multichoice-a}", "{tag_q1-multichoice-b}", "{tag_q1-multichoice-c}", "{tag_q1-multichoice-d}", "{tag_q1-correct-answer}", "{tag_q-multichoice-1}", "{tag_q-t/f-1}", "{tag_s-ratings-1}", "{tag_s-shortanswer-1}", "{tag_q1-pass/fail}");
question[2] = new Question("2", "{tag_q2-question}", "{tag_q2-answer-type}", "{tag_q2-multichoice-a}", "{tag_q2-multichoice-b}", "{tag_q2-multichoice-c}", "{tag_q2-multichoice-d}", "{tag_q2-correct-answer}", "{tag_q-multichoice-2}", "{tag_q-t/f-2}", "{tag_s-ratings-2}", "{tag_s-shortanswer-2}", "{tag_q2-pass/fail}");
question[3] = new Question("3", "{tag_q3-question}", "{tag_q3-answer-type}", "{tag_q3-multichoice-a}", "{tag_q3-multichoice-b}", "{tag_q3-multichoice-c}", "{tag_q3-multichoice-d}", "{tag_q3-correct-answer}", "{tag_q-multichoice-3}", "{tag_q-t/f-3}", "{tag_s-ratings-3}", "{tag_s-shortanswer-3}", "{tag_q3-pass/fail}");
var userScore = "{tag_total score}";
var passingScore = "{tag_required score to pass}";
var showAnswers = "{tag_show answers}";
So now that you see how the Data is stored, here is the code for the page that it is output on. Note that I left out Step 2, the code that runs the search - I know this works, so I didn't think you would need to see it.
<div class="row">
<div class="small-12 columns">
<div class="quiz-survey-search" id="qs-results" style="display: block;"> {module_webappscustomer,19627,l,,,_self,true,1,true,1} </div>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<div class="correct" id="correct" style="display: none;">
<h2 id="quiz-headline-1" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">Good work completing this chapter!<br />
Your score is:</h4>
<div class="large-score" id="score-1"></div>
</div>
<div class="incorrect" id="incorrect" style="display: none;">
<h2 id="quiz-headline-2" style="line-height:110%;margin-bottom:1rem;"></h2>
<h4 style="text-align:center;margin:1.5rem 3rem;color:black!important;">You did not achieve the required passing score. Please review the materials and take the quiz again to complete this chapter.</h4>
<div class="large-score" id="score-2" style="margin:3rem 0rem;"></div>
</div>
<div class="survey" id="survey" style="display: none;">
<h2>Thank you for completing the survey.</h2>
<h4>Your answers have been submitted.</h4></div>
</div>
<div id="correct-answers" style="display: none;">
<h3 style="text-decoration: underline;">Correct Answers</h3>
<p style="font-weight: bold;">Although you passed the quiz you had one or more answers that were incorrect.
Below are the correct answers.</p>
<div class="row">
<div id="incorrectQuestions"></div>
</div>
</div>
</div>
<script>
var quizsurveyDiv = document.getElementById('qs-results').innerHTML;
if (quizsurveyDiv == " ") {
var element = '{module_url,AllIDs}';
var arrayOfStrings = element.split("-");
document.getElementById('CAT_Custom_206').value = arrayOfStrings[0];
document.getElementById('CAT_Custom_2').value = arrayOfStrings[1];
document.getElementById('CAT_Custom_3').value = arrayOfStrings[2];
catcustomcontentform9225.submit();
} else {
if (quizSurvey == "Quiz") {
var qNumber = 0;
var qNumbers = function() {
for (i = 0; i <= 14; i++) {
if (question[i].questionText !== "") {
qNumber = qNumber + 1;
console.log('here - ' + qNumber);
};
};
};
var writeDivs = function() {
var incorrectQDiv = "";
for (i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
incorrectQDiv = document.getElementById('incorrectQuestions').innerHTML;
document.getElementById('incorrectQuestions').innerHTML = incorrectQDiv + "<div class='small-12 medium-6 columns incorrectQ' id='incorrectQ-" + question[i].questionNumber + "'>Hi!!</div>";
console.log('here2 - ' + qNumber);
} else if (question[i].qPassFail == "1") {
};
};
};
var writeQContent = function() {
for (var i = 1; i <= qNumber; i++) {
if (question[i].qPassFail == "0") {
if (question[i].answerType == "True/False") {
var qUserAnswer = question[i].userTF;
} else {
qUserAnswer = question[i].userMultichoice;
};
document.getElementById('incorrectQ-' + question[i].questionNumber).innerHTML = "<p><span class='pinkNum'>" + question[i].questionNumber + "</span>" + question[i].questionText + '</p><div class="row"><div class="small-12 small-push-12 medium-6 columns"><p><span class="pink-title">Your Answer: ' + qUserAnswer + '</span><br/><div id="incorrectA-' + question[i].questionNumber + '"></div></p></div><div class="small-12 small-pull-12 medium-6 columns"><p><span class="pink-title">Correct Answer: ' + question[i].correctAnswer + '</span><div id="correctA-' + question[i].questionNumber + '"></div></p></div></div>';
};
if (question[i].qPassFail == "0" && question[i].answerType == "Multiple Choice") {
var correctADiv = "correctA-" + question[i].questionNumber; console.log(correctADiv);
if (question[i].correctAnswer == "A") {
document.getElementById(correctADiv).innerHTML = question[i].answerA;
} else if (question[i].correctAnswer == "B") {
document.getElementById(correctADiv).innerHTML = question[i].answerB;
} else if (question[i].correctAnswer == "C") {
document.getElementById(correctADiv).innerHTML = question[i].answerC;
} else {
document.getElementById(correctADiv).innerHTML = question[i].answerD;
};
};
};
};
var showTheAnswers = function() {
if (quizPassFail == "1") {
document.getElementById('quiz-headline-1').innerHTML = "You passed the quiz: " + quizName;
document.getElementById('score-1').innerHTML = '<span class="large-score">' + totalScore + '%</span>';
document.getElementById('correct').style.display = "block";
if (showAnswers == "1") {
if (totalScore != "100") {
document.getElementById('correct-answers').style.display = "block";
} else if (showAnswers != "1" || totalScore == "100") {
document.getElementById('correct-answers').style.display = "none";
};
};
} else {
document.getElementById('quiz-headline-2').innerHTML = "Unfortunately you did not pass the quiz: " + quizName ;
document.getElementById('score-2').innerHTML = '<div class="hide-for-small medium-1 large-2 columns"> </div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="userScore"></span><br/>Your Score</p></div><div class="small-6 medium-5 large-4 columns"><p><span class="large-score" id="requiredScore"></span><br />Required Score</p></div><div class="hide-for-small medium-1 large-2 columns"> </div>';
innerScores();
document.getElementById('incorrect').style.display = "block";
};
};
var innerScores = function() {
document.getElementById('userScore').innerHTML = totalScore + "%";
document.getElementById('requiredScore').innerHTML = requiredScore + "%";
console.log('innerScores');
};
if (showAnswers == "1" && totalScore != "100") {
qNumbers();
writeDivs();
writeQContent();
showTheAnswers();
} else if (showAnswers == "0" && totalScore != "100") {
showTheAnswers();
} else {
showTheAnswers();
}
} else if (quizSurvey == "Survey") {
document.getElementById('survey').style.display = "block";
};
courseCompletePass();
};
Thank you for any and all possible help. This has been an extremely difficult coding process and any help would be greatly appreciated!

Why doesn't my script work with checkboxes?

I am trying to make a little "game" and for some reason, if I try and get the checked of a checkbox, my script will flip out... sometimes it works, sometimes it just stops executing. Is there some sort of an error I missed?
<html>
<head>
<title>Untitled Document</title>
<script>
var check = "showcheck";
var number = 1234;
var lvl = 1;
var oldlvl = 1;
var multiplier = 10000;
var start = 1;
function exefunction() {
document.getElementById("boxv").focus();
if (check == "showcheck") {
document.getElementById("message").innerHTML = "What was the number?";
document.getElementById("num").style.display = "none";
document.getElementById("box").style.display = "inline";
document.getElementById("boxv").focus();
check = "checknum";
}
else if (check == "checknum") {
if (document.getElementById("boxv").value == number) {
document.getElementById("message").innerHTML = "CORRECT!";
document.getElementById("boxv").style.color = "#00DD00";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
lvl++;
}
else if (document.getElementById("boxv").value != number) {
document.getElementById("message").innerHTML = "INCORRECT!";
document.getElementById("boxv").style.color = "#DD0000";
document.getElementById("boxv").value = number;
document.getElementById("level").innerHTML = "Level: " + lvl;
if (lvl>1) {lvl--;}
loselife();
}
check = "showmem";
}
else if (check == "showmem") {
if (lvl == oldlvl + 10) {
oldlvl = lvl;
multiplier = multiplier * 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
else if (lvl < oldlvl) {
oldlvl = lvl - 10;
multiplier = multiplier / 10;
document.getElementById("boxv").maxLength = multiplier.toString().length - 1;
}
number = Math.floor(Math.random() * multiplier / 10 * 9) + multiplier / 10;
document.getElementById("boxv").style.color = "#000000";
document.getElementById("boxv").value = "";
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").innerHTML = number;
document.getElementById("num").style.display = "inline";
document.getElementById("box").style.display = "none";
check = "showcheck";
}
}
function loselife(){
var life = 4;
var hearts = "♥ ";
alert(document.getElementById("lifebox").checked);
}
function submitenter() {
var keycode = window.event.keyCode;
if (keycode == 13) {
if (start === 0) {exefunction();}
else {startfunc();}
}
if (keycode < 47 || keycode > 58) {
return false;
}
}
function startfunc() {
document.getElementById("button").innerHTML = '<input name="" type="button" value="OK" onClick="exefunction()"/>';
document.getElementById("level").innerHTML = "Level: " + lvl;
document.getElementById("message").innerHTML = "Memorize this number: ";
document.getElementById("num").style.display = "inline";
document.getElementById("boxv").value = "";
document.getElementById("box").style.display = "none";
if (document.getElementById("lifecheck").checked === true) {
document.getElementById("life").innerHTML = "♥ ♥ ♥ ♥ ♥ ";
}
else if (document.getElementById("lifecheck").checked === false) {
document.getElementById("life").innerHTML = "";
}
if (document.getElementById("timercheck").checked === true) {
document.getElementById("timer").innerHTML = "3:00";
}
else if (document.getElementById("timercheck").checked === false) {
document.getElementById("timer").innerHTML = "";
}
start = 0;
}
function tests() {
alert(lfckv);
}
</script>
<style type="text/css">
#level, #life, #timer{
color: #666;
}
* {
text-align: center;
}
#num {
display: none;
}
#num {
font-size: x-large;
}
#body {
margin-top: 250px;
margin-right: auto;
margin-bottom: 100px;
margin-left: auto;
}
body {
background-color: #6FF;
}
</style></head>
<body onKeyPress="return submitenter()" >
<div id="body">
<span id="level"></span>
<table align="center">
<tr>
<td width="200" height="50" align="center" valign="middle"><span id="message">What level would you like to begin at?</span></td>
<td width="200" height="50" align="center" valign="middle"><span id="num">1234</span><span id="box"><input type="text" id="boxv" maxlength="4" value="1"/></span></td>
</tr>
</table>
<table align="center">
<tr>
<td width="200" id="life"><label><input id="lifecheck" type="checkbox" >Lives</label></td>
<td id="button"><input type="button" value="OK" onClick="startfunc()"/></td>
<td width="200" id="timer"><label><input id="timercheck" type="checkbox" >Timer</label></td>
</tr>
</table>
<input name="" type="button" onClick="tests()" value="tests()">
</div>
</body>
</html>
lifebox isnt defined in the loselife() function. Plus, also check the test() function, that alert() statement has a variable that isnt defined.
If you are using Google chrome (or any other browser that can help you debug), I would suggest you to debug through your lines of code.
I think you're better off using simple equality for checking the state of your checkboxes, because I'm pretty the outcome is not a Boolean.
So it would be something like that :
if (document.getElementById("lifecheck").checked == true) {
or simply
if (document.getElementById("lifecheck").checked) {
instead of
if (document.getElementById("lifecheck").checked === true) {
Ahah! I figured out the problem. Apparently, when I set the visibility of the checkbox to none, it also set the checkvalue to null for some reason. I had expected it to keep the checkvalue, but for some reason it does not.

Categories