I'm constructing a quiz application and am having trouble verifying whether or not user answers are correct. The quiz contains 10 questions, and uses radio buttons to get answers from the user. For some questions, none of the answers register as correct, and for some of the other questions, all of the answers register as correct.
Each question has its own 'questionClass,' outlined like so:
function questionClass (q, a1, a2, a3, a4, n, c) {
this.question = q;
this.answer1 = a1;
this.answer2 = a2;
this.answer3 = a3;
this.answer4 = a4;
this.number = n;
this.correct = c;
Each of the question classes are created with the following formula:
var questionOne = new questionClass("quotation to be analyzed", 'answer1','answer2','answer3','answer4', number, 'correct');
questions.push(questionOne);
The function for verifying whether or not the user got the correct answer is here:
this.checkAnswer=checkAnswer;
function checkAnswer() {
if ($('input:radio[name=" ' + this.number + ' "]:checked').val() == this.correct) {
score++;
}
else if ($('input:radio[name=" ' + this.number + ' "]:checked').val() == this.correct) {
score++;
}
else if ($('input[id=" ' + this.answer3 + ' "]:checked') && (this.answer3 == this.correct)) {
score++;
}
else if ($('input[id=" ' + this.answer4 + ' "]:checked') && (this.answer4 == this.correct)) {
score++;
}
else {
console.log("you got the wrong answer");
}
}
The function for moving between questions is as follows:
$("#continue").click(function(){
counter++;
if (counter == 1) {
questions[x].display();
}
else if ((counter >= 1) && (counter <= 10)) {
if (questions[x].isSelected()) {
$('.warning').html("");
questions[x].checkAnswer();
$('.score').html("<p>Your score is " + score + " out of 10</p>");
x++;
if (x < 10){
questions[x].display();
}
}
}
else if ((counter >= 11) && (!questions[x].isSelected())) {
return;
}
else {
$('.warning').html("");
questions[x].checkAnswer();
$('.score').empty();
$('#container').html('<h1>You scored ' + score + ' out of 10.</h1></br>');
$('#container').append('<input type="button" id="tryAgain" value="Try Again!">');
}
});
The application can be viewed at this link:
http://dl.dropboxusercontent.com/u/91499081/QuizApp/quizApp.html
Fiddle http://jsfiddle.net/MCjna/
Related
I'm working on a somewhat simply dice game but I can't get it to display the alert popup when I click the button.
I'm also trying to figure out the simplest way to check if housescore or myscore = maxscore then alert "congratulations, you win" or "sorry, you lost"
Here is my code:
var myscore = 0;
var maxScore = 100;
var housescore = 0;
function rollDice() {
var x = Math.floor(Math.random() * 6) + 1;
var y = Math.floor(Math.random() * 6) + 1;
if (x + y == 7 || 11) {
housescore = (housescore + 10);
alert("CRAPS" + " Your Score is " + "Player: " + myscore + "House: " + housescore);
} else if (x == y && x + y == isEven(n)) {
myscore = (myscore + 10);
alert("Even Up" + " Your Score is " + "Player: " + myscore + "House: " + housescore);
}
if (x == y && x + y == isOdd(n)) {
housescore = (housescore + 10);
alert("Odd Ball" + " Your Score is " + "Player: " + myscore + "House: " + housescore);
} else {
alert("You rolled a " + x + " and a " + y + " Your Score is " + "Player: " + myscore + "House: " + housescore);
}
}
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
<input type="button" value="Roll The Dice" onClick="rollDice()" />
This is what I think you're after. I broke down your ifs to handle both cases where x == y in one branch, and used a simple mod operation to determine whether a die roll was even, and an else to handle the odd die rolls.
var myscore = 0;
var maxScore = 100;
var housescore = 0;
function rollDice() {
var x = Math.floor(Math.random() * 6) + 1;
var y = Math.floor(Math.random() * 6) + 1;
var total = x + y;
msg = "You rolled " + x + "," + y + " = " + total + "\n";
if (total == 7 || total == 11) {
housescore += 10;
msg += "CRAPS";
} else if (x == y) { // this condition contains two possible outcomes, handle both within this else if
if (x % 2 == 0) {
myscore += 10;
msg += "Even Up";
} else {
housescore += 10;
msg += "Odd Ball";
}
}
msg += " Your Score is " + "Player: " + myscore + ", House: " + housescore;
alert(msg);
}
<!DOCTYPE html>
<html>
<body>
<input type="button" value="Roll The Dice" onClick="rollDice()" />
</body>
</html>
Code like this is wrong:
if (x == y && x + y == isEven(n))
You haven't declared an n variable. And it makes no sense to compare the addition of two numbers to the true or false value that isEven() and isOdd() return. I think what you meant was:
if (x == y && isEven(x + y))
But when the two numbers are equal, adding them together will always be even, so I'm not sure what the point of that test is. Maybe you mean:
if (x == y && isEven(x))
I'm not familiar with a rule in Craps where the house or player win depending on whether equal dice are even or odd.
This is also wrong:
if (x == 7 && y == 11)
x and y are numbers from 1 to 6, so they can't be 7 or 11. In craps you add the two dice, so this should be:
if (x + y == 7 || x + y == 11)
There's little need for both isEven() and isOdd() functions -- a number is odd if it's not even.
<!DOCTYPE html>
<html>
<body>
<input type="button" value="Roll The Dice" onClick="rollDice()" />
<br />
<script type="text/javascript">
var score = 0;
var maxScore = 50;
var rolls = 0;
var maxRolls = 20;
function rollDice()
{
var x = Math.floor( Math.random() * 6 ) + 1;
var y = Math.floor( Math.random() * 6 ) + 1;
if( x == y )
{
score = getScore( x );
alert("You threw a Double " + x + " Your Score is "+ score);
}
else
{
alert("You threw a " + x + " and a " + y + " Your Score is " + score);
}
rolls++;
if (rolls == maxRolls && score < maxScore)
{
alert("Sorry You Lose!");
score = 0;
rolls = 0;
return;
}
else if (score >= maxScore)
{
alert("Congratulations You Win!");
score = 0;
rolls = 0;
return;
}
}
function getScore(x)
{
switch( x )
{
case 1:
score += 5;
break;
case 2:
score += 5;
break;
case 3:
score = 0;
break;
case 4:
score += 5;
break;
case 5:
score += 5;
break;
case 6:
score += 25;
break;
}
return score;
}
</script>
</body>
</html>
</html>
I'm trying to improve the following script by adding some randomness to it. Because right now it only bets on the "double_your_btc_bet_hi_button" id.
My idea is to generate a random number and make the bet based the its outcome. But I'm not sure how I supose to do that.
The id of the other bet buttom is "double_your_btc_bet_lo_button".
var minstake = 0.00000001; // valor base
var autorounds = 100; // n° de rolls
var handbrake = 0.0001; // valor lose pause game
var autoruns = 1;
function playnow() {
if (autoruns > autorounds ) { console.log('Limit reached'); return; }
document.getElementById('double_your_btc_bet_hi_button').click();
setTimeout(checkresults, 123);
return;}
function checkresults() {
if (document.getElementById('double_your_btc_bet_hi_button').disabled === true) {
setTimeout(checkresults, 246);
return;
}
var stake = document.getElementById('double_your_btc_stake').value * 1;
var won = document.getElementById('double_your_btc_bet_win').innerHTML;
if (won.match(/(\d+\.\d+)/) !== null) { won = won.match(/(\d+\.\d+)/)[0]; } else { won = false; }
var lost = document.getElementById('double_your_btc_bet_lose').innerHTML;
if (lost.match(/(\d+\.\d+)/) !== null) { lost = lost.match(/(\d+\.\d+)/)[0]; } else { lost = false; }
if (won && !lost) { stake = minstake; console.log('Bet #' + autoruns + '/' + autorounds + ': Won ' + won + ' Stake: ' + stake.toFixed(8)); }
if (lost && !won) { stake = lost * 2.1; console.log('Bet #' + autoruns + '/' + autorounds + ': Lost ' + lost + ' Stake: ' + stake.toFixed(8)); }
if (!won && !lost) { console.log('Something went wrong'); return; }
document.getElementById('double_your_btc_stake').value = stake.toFixed(8);
autoruns++;
if (stake >= handbrake) {
document.getElementById('handbrakealert').play();
console.log('Handbrake triggered! Execute playnow() to override');
return;
}
setTimeout(playnow, 111);
return;
}playnow()
I've tried to use Math.random but now it only bets lo and only plays once.
var minstake = 0.00000001; // valor base
var autorounds = 99999; // n° de rolls
var handbrake = 0.0001; // valor lose pause game
var autoruns = 1;
function getRandomNumber() {Math.floor(Math.random() * 2) + 1;
};
function playnow() {
if (autoruns > autorounds ) { console.log('Limit reached'); return; }
if (getRandomNumber!==1) {
document.getElementById('double_your_btc_bet_lo_button').click();
setTimeout(checkresultslo, 123);
return;
function checkresultslo() {
if (document.getElementById('double_your_btc_bet_lo_button').disabled === true) {
setTimeout(checkresultslo, 246);
return;}}}
if (getRandomNumber!==2) {
document.getElementById('double_your_btc_bet_hi_button').click();
setTimeout(checkresultshi, 123);
return;
function checkresultshi() {
if (document.getElementById('double_your_btc_bet_hi_button').disabled === true) {
setTimeout(checkresultshi, 246);
return;}}}
}
var stake = document.getElementById('double_your_btc_stake').value * 1;
var won = document.getElementById('double_your_btc_bet_win').innerHTML;
if (won.match(/(\d+\.\d+)/) !== null) { won = won.match(/(\d+\.\d+)/)[0]; } else { won = false; }
var lost = document.getElementById('double_your_btc_bet_lose').innerHTML;
if (lost.match(/(\d+\.\d+)/) !== null) { lost = lost.match(/(\d+\.\d+)/)[0]; } else { lost = false; }
if (won && !lost) { stake = minstake; console.log('Bet #' + autoruns + '/' + autorounds + ': Won ' + won + ' Stake: ' + stake.toFixed(8)); }
if (lost && !won) { stake = lost * 2.1; console.log('Bet #' + autoruns + '/' + autorounds + ': Lost ' + lost + ' Stake: ' + stake.toFixed(8)); }
if (!won && !lost) { console.log('Something went wrong');}
document.getElementById('double_your_btc_stake').value = stake.toFixed(8);
autoruns++;
if (stake >= handbrake) {
document.getElementById('handbrakealert').play();
console.log('Handbrake triggered! Execute playnow() to override');
}
setTimeout(playnow, 111);
playnow()
I need help with how to make my code's if else statement to only run once and I was wondering if I followed all the instructions that were asked for this assignment. Also, i may have some errors or placement issues. I am a beginner javascript user as I never used the program before this. The instructions are below as followed:
Run an if/else statement to see if age is less than 60, then display alerts depending on the result
Push a third question to the questions array
Push the corresponding array of answers to the answers array
Add if and else if statements to the score-checking to increment the score at different levels for each answer: 3 points, 2 points, or 1 point depending on the user’s choice. These should be implemented for all three questions. Try to use a for loop to cycle through all the questions and answers, and consider using the index in the array for the scoring system.
-Add <br>Score: plus the user’s score to their paragraph (id='myParagraph') by using document.getElementById to change the innerHTML
Add an additional prompt asking the user to calculate the results of a basic math question
Increment the user’s score by 5 if their answer to the math question is equal to the results of the same math question as an expression: make sure the equation is part of your if statement.
Code below:
var question = ['What is your quest?', 'What is the airspeed of an unladen swallow?', 'What planet\'s moon can more liquid water than all of Earth\'s oceans?'];
var score = 0;
var answers = [
['To seek the grail', 'I don\'t know that', 'To be in Monty Python'],
['African or European?', '92', '24'],
['Europa', 'Titan', 'Pandora']
];
console.log(answers);
console.log(answers[1][0]);
var name = prompt('What is your name?');
//alert('A message;);
document.getElementById('myParagraph').innerHTML = 'Hello ' + name + '!';
document.getElementById('myScore').innerHTML = 'You scored ' + score + 'points!';
console.log(typeof name);
var age = prompt('How old are you?');
console.log(typeof age);
age = Number(age);
console.log(typeof age);
if (age < 60) {
alert(age);
}
for (var i = 0; i <= age; i++) {
document.write(i);
document.write(' ');
}
var math = prompt('What is 16+2-1*3=?');
console.log(typeof math);
math = Number(math);
if (math === 15) {
alert(math);
} else {
alert('You are incorrect');
}
for (var j = 0; j <= math; i + 5) {
document.write(j);
document.write(' ');
}
var guess = prompt(question[0] + '\n\u2022 ' + answers[0][0] + '\n\u2022 ' + answers[0][1] + '\n\u2022 ' + answers[0][2]);
if (guess === answers[0][0]) {
score += 3;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[0][1]) {
score += 2;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[0][2]) {
score += 1;
console.log(score + ' ' + 'points earned!');
}
var guess = prompt(question[1] + '\n\u2022 ' + answers[1][0] + '\n\u2022 ' + answers[1][1] + '\n\u2022 ' + answers[1][2]);
if (guess === answers[1][0]) {
score += 1;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[1][1]) {
score += 2;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[1][2]) {
score += 3;
console.log(score + ' ' + 'points earned!');
}
var guess = prompt(question[2] + '\n\u2022 ' + answers[2][0] + '\n\u2022 ' + answers[2][1] + '\n\u2022 ' + answers[2][2]);
if (guess === answers[2][0]) {
score += 3;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[2][1]) {
score += 2;
console.log(score + ' ' + 'points earned!');
} else if (guess === answers[2][2]) {
score += 1;
console.log(score + ' ' + 'points earned!');
}
<br id="myScore">
<p id="myParagraph">A paragraph!</p>
</br>
You have an infinite loop here:
for (var j = 0; j <= math; i + 5) {
document.write(j);
document.write(' ');
}
Since you never modify j, j <= math is always true, so the loop never ends.
I don't see any reason for this loop in the first place. The problem specification says to add 5 to the user's score if they get the math question right. So you should do:
if (math === 15) {
alert(math);
score += 5; // Add 5 to the user's score
} else {
alert('You are incorrect');
}
this is what i have but i need to record the problems that are wrong and have the user answer them until there right, keep prompting the user for the problem until its right this was a 4 part problem and part3 is to have the same problem repeat until its completed
ex.(7+1=6) repeat(7+1=4) repeat (7+1=8) next problem
the user has to complete 5 problems and they have to be correct
<html>
<script>
var file=0;
var fileIndex=new Array();
var user=prompt("what is "+a+" + "+b);
var arr=[user,user,user,user,user];
var a=Math.floor(Math.random()*11);
var b=Math.floor(Math.random()*11);
var answer=parseInt(a+b);
var user=prompt("what is "+a+" + "+b);
while (user != answer && file++ != 4) {
fileIndex.push(user);
user = prompt("what is " + a + "+" + b);
} else {
alert("answer is:" + answer);
}
}//close for
</script>
Update:
var a = 1,
b = 1;
var answer = a + b,
tick = 0;
var file_index = [], copy;
function randomize() {
a = Math.floor(Math.random() * 11);
b = Math.floor(Math.random() * 11);
answer = a + b;
}
while (1)
{
if ((copy = prompt("What is " + a + " + " + " b?", 0)) != answer)
{
if (!copy) break;
file_index.push(copy);
randomize();
} else if (tick == 4) {
break;
} else {
++tick;
}
}
jsFiddle Demo
To preface this, we are a small organization and this system was built by someone long ago. I am a total novice at javascript so I have trouble doing complicated things, but I will do my best to understand your answers. But unfortunately redoing everything from scratch is not really an option at this point.
We have a system of collecting data where clients use a login to verify a member ID, which the system then uses to pull records from an MS Access database to .ASP/html forms so clients can update their data. One of these pages has the following function that runs on form submit to check that data in fields a/b/c sum to the same total as d/e/f/g/h/i. It does this separately for each column displayed (each column is a record in the database, each a/b/c/d/e/f is a field in the record.)
The problem is with this section of the function:
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
etc.
It should use javascript FOR to loop through each record and test to see if they sum to the same thing.
In Firefox and IE this is working properly; the fields sum properly into "sumByType" and "sumByTrack". You can see below I added a little alert to figure out what was going wrong:
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
In Chrome, that alert tells me that the components of "sumByType" and "sumByTrack" (the various "milesXXXXX" variables) are undefined.
My question is: Why in Chrome is this not working properly, when in IE and FFox it is? Any ideas?
Full function code below:
function submitCheck(formy, recCnt) {
//2/10/03: added milesQuad
//---------------checks Q#4 that Line Mileage by type is the same as by track
var milesElev = new Array();
var milesSurf = new Array();
var milesUnder = new Array();
var milesSingle = new Array();
var milesDouble = new Array();
var milesTriple = new Array();
var milesQuad = new Array();
var milesPent = new Array();
var milesSex = new Array();
var sumByType = 0;
var milesLineTrack = new Array(); //this is for Q5 to compare it to mileage by trackage
var j = 0; var sumByTrack = 0; var liney; var yrOp;
//var str = "document.frm.milesElev" + j;
//alert(str.value);
for (var i in document.frm) {
if (i.substring(0, i.length - 1) == "milesElev") {
milesElev[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSurf") {
milesSurf[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesUnder") {
milesUnder[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSingle") {
milesSingle[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesDouble") {
milesDouble[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesTriple") {
milesTriple[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesQuad") {
milesQuad[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesPent") {
milesPent[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSex") {
milesSex[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length -1) == "milesLineTrack") {
milesLineTrack[parseInt(i.substring(i.length-1, i.length))] = document.frm[i].value; } //12/13/02 used to be parseFloat(document.frm[i].value)
if (i.substring(0,5)=="Lines") {
liney = document.frm[i].value;
if (parseInt(liney)<1 || isNaN(liney)) {
alert("Each mode must have at least 1 line. Please correct the value in question #2.");
document.frm[i].select(); return false; }}
if (i.substring(0,8)=="yearOpen") {
yrOp = document.frm[i].value;
if (parseInt(yrOp)<1825 || isNaN(yrOp)) {
alert("Please enter a year after 1825 for question #3");
document.frm[i].select(); return false; }
}
}
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
//---------------to round sumByTrack and sumByType from a long decimal to a single decimal place, like frm 7.89999998 to 7.9.
sumByTrack = sumByTrack * 10;
if (sumByTrack != parseInt(sumByTrack)) {
if (sumByTrack - parseInt(sumByTrack) >= .5) {
//round up
sumByTrack = parseInt(sumByTrack) + 1; }
else { //truncate
sumByTrack = parseInt(sumByTrack); }}
sumByTrack = sumByTrack / 10;
sumByType = sumByType * 10;
if (sumByType != parseInt(sumByType)) {
if (sumByType - parseInt(sumByType) >= .5) {
//round up
sumByType = parseInt(sumByType) + 1; }
else { //truncate
sumByType = parseInt(sumByType); }}
sumByType = sumByType / 10;
//-------------end of rounding ---------------------------
if (sumByType != sumByTrack) {
if (isNaN(sumByType)) {
sumByType = "(sum of 4.a., b., and c.) "; }
else {
sumByType = "of " + sumByType; }
if (isNaN(sumByTrack)) {
sumByTrack = "(sum of 4.d., e., f., g., h., and i.) "; }
else {
sumByTrack = "of " + sumByTrack; }
alert("For #4, the 'End-to-End Mileage By Type' " + sumByType + " must equal the 'End-to-end Mileage By Trackage' " + sumByTrack + ".");
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
return false;
}
//alert (milesLineTrack[j] + " " + milesSingle[j] + " " + 2*milesDouble[j] + " " + 3*milesTriple[j] + " " + 4*milesQuad[j] + " " + 5*milesPent[j] + " " + 6*milesSex[j]);
var singDoubTrip = (milesSingle[j] + 2*milesDouble[j] + 3*milesTriple[j] + 4*milesQuad[j] + 5*milesPent[j] + 6*milesSex[j])
//----------round singDoubTrip to one digit after the decimal point (like from 6.000000001 to 6.0)
singDoubTrip = singDoubTrip * 10;
if (singDoubTrip != parseInt(singDoubTrip)) {
if (singDoubTrip - parseInt(singDoubTrip) >= .5) {
//round up
singDoubTrip = parseInt(singDoubTrip) + 1; }
else { //truncate
singDoubTrip = parseInt(singDoubTrip); }}
singDoubTrip = singDoubTrip / 10;
//----------end round singDoubTrip-----------------------------------------
if (parseFloat(milesLineTrack[j]) != singDoubTrip) {
//var mlt = milesLineTrack[j];
//if isNaN(milesLineTrack[j]) { mlt =
alert("For column #" + (j+1) + ", the mainline passenger track mileage of " + milesLineTrack[j] + " must equal the single track plus 2 times the double track plus 3 times the triple track plus 4 times the quadruple track plus 5 times the quintuple track plus 6 times the sextuple track, which is " + singDoubTrip + ".");
return false;
}
}
//---------------------end of checking Q#4----------------
//return false;
}
I think for (var i in document.frm) is the problem. You should not enumerate a form element, there will be plenty of unexpected properties - see Why is using "for...in" with array iteration a bad idea?, which is especially true for array-like objects. I can't believe this works properly in FF :-)
Use this:
var ele = document.frm.elements; // or even better document.getElementById("frm")
for (var i=0; i<ele.length; i++) {
// use ele[i] to access the element,
// and ele[i].name instead of i where you need the name
}
Also, you should favour a loop over those gazillion of if-statements.