I was wondering about how I might collect user’s scores for a math quiz I made - javascript

I want to collect user’s scores from my GitHub page (theratcoder.github.io). I have used the following JS code (embedded in my HTML document) to create my quiz.
var score = 0;
var times33 = window.prompt("3 x 3");
switch(times33) {
case "9":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var subtract5221 = window.prompt("52 - 21");
switch(subtract5221) {
case "31":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var add56 = window.prompt("5 + 6");
switch(add56) {
case "11":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var divide183 = window.prompt("18 / 3");
switch(divide183) {
case "6":
document.write("correct - ");
score++;
break;
default:
document.write("incorrect - ");
break;
}
var finishing_text;
switch(score) {
case 4:
finishing_text = "Great job!";
break;
case 3:
finishing_text = "Well done.";
break;
case 2:
finishing_text = "Better luck next time!";
break;
case 1:
finishing_text = "You need to work on your math!";
break;
default:
finishing_text = "You really need to work on your math!";
break;
}
var submit = window.confirm("Do you want to submit this quiz?");
var percent = score / 4 * 100;
if (submit) {
document.write("Your final score is " + score + " out of 4 (" + percent + "%). ");
document.write(finishing_text);
}
else {
location.reload();
}
I want to collect the values of the variable “score” so that I can get an idea of how people generally do on my quiz.

In order to do something like that, you'll need two things, a way to get the data to some form of storage, and the storage itself.
Unless some things have changed, github.io sites are static content only, so there's no server running in the background that you can access and communicate with your storage from, just your static content being served by the github.io service and running in the user's browser.
So the basic answer is you can't. But that's not true and there's always a hack if you're willing to do something gnarly. (I assume this is just for fun?)
If that's the case, you could run a server on your computer at home or something. Then when the user answers a question you add a call to the server on your computer at home and it takes that data and saves it and aggregates it however you want.
But end of the day if you want to store things about your users, you're probably going to want to have a dynamic website.
Although, maybe take a look at this if you're determined: https://medium.com/pan-labs/dynamic-web-apps-on-github-pages-for-free-ffac2b776d45 -- it's something like the "send data to your own computer" step, but using the free tier of firebase instead.

Related

How to display images using Switch statement?

I'm working on a Mass Effect personality quiz that has been adapted from the EasyDamus D&D quiz from the 90s, and I'm having trouble with the results page. Namely, I'm trying to include an image to match each result, but I don't know how to do so when the code implements the results using a switch statement. Here is a snippet of the code:
var win = window.open("", "win","width=900,height=550,top=25,left=50,toolbar=yes,menubar=yes,scrollbars=yes,resizable=yes,location=yes");
with (win.document) {
open("text/html", "replace");
write("<html><head><link rel='stylesheet' type='text/css' href='index.css'><title>Your Results Are In!\<\/title>\<\/head>");
write("<body text='#FFFFFF' font-family='massEffect' link='#5555FF' vlink='#6666EE' bgcolor='#F2ECDA' background='images/space.png'>");
write("<center><h2><b><font color='#FFFFFF'>You Are A:\<\/font>\<\/b>\<\/h2>\<\/center>");
write("<br><center><h1><b>");
switch (race) {
case "human": write("Human\<\/b> "); break;
case "asari": write("Asari\<\/b> "); break;
case "turian": write("Turian\<\/b> "); break;
case "salarian": write("Salarian\<\/b> "); break;
case "krogan": write("Krogan\<\/b> "); break;
case "quarian": write("Quarian\<\/b> "); break;
case "geth": write("Geth\<\/b> "); break;
case "volus": write("Volus\<\/b> "); break;
case "rachni": write("Rachni\<\/b> "); break;
case "batarian": write("Batarian\<\/b> "); }
switch (primclass) {
case "soldier": write(" Soldier"); break;
case "infiltrator": write(" Infiltrator"); break;
case "engineer": write(" Engineer"); break;
case "adept": write(" Adept"); break;
case "sentinel": write(" Sentinel"); break;
case "vanguard": write(" Vanguard"); }
switch (secclass) {
case "soldier": write("/Soldier"); break;
case "infiltrator": write("/infiltrator"); break;
case "engineer": write("/Engineer"); break;
case "adept": write("/Adept"); break;
case "sentinel": write("/Sentinel"); break;
case "none": write(""); break;
case "vanguard": write("/Vanguard"); }
write("<br><h2><br>Race:<br></h2>");
switch (race) {
case "human": `
The last line is the flavor text for each result, and while there's no issue with how it displays, I'm trying to find a way to have an image precede it. I have the pictures available, most of them in array called from a local folder. What would be the best way to have the images appear?
I've searched for solutions for a few weeks, most of which recommend event listeners, but I haven't been able to get it to work for me.
This code does a lot of stuff. First of all with switch statement, it should set up some variable for a particular case. Also its always a good practice to provide a default case for each switch-statement.
function decideOnRace(race) {
let result = '';
switch (race) {
case "human":
result = "Human\<\/b> ";
break;
default:
result = 'something else";
break;
}
}
// place this accordingly
const raceTextToWrite = decideOnRace(race);
write(raceTextToWrite);
Following this practice for all the different cases should help you progress e.g., for secclass, primclass, etc.

(Javascript prompt app ) switchcase inside switchcase will not run

I am making an app (idk what to call it) that shows up as a prompt and alert.
However, my code seems to unable to run a switchcase inside a switchcase which I use to add an order into a cart and also use to show the content of the cart.
Another way of saying what my problem is:
I cannot add items to my cart
I cannot access my cart (the prompt just closes itself)
To be more clear I will include my code below along with a codepen link of it and I will comment where I think the problems are.
All input is greatly appreciated.
Thanks!
arrayCart =[];
totalBill = parseInt(0);
cartContent = arrayCart.length;
for(;;)
{
userInput = parseInt(prompt('1. Menu\n2. Your Cart\n3. Payment\n4. Exit'))
switch(userInput)
{
// This is to go to Menu
case 1:
inputPesanan = prompt('Silahkan pilih menu yang diinginkan:\n1. Paket Bento A\n2. Paket Bento B\n3. Paket Bento C')
// I think the 1st problem starts here
switch(inputPesanan)
{
case 1:
arrayCart.push('Paket Bento A - Rp20.000\n');
totalBill += parseInt(20000);
break;
case 2:
arrayCart.push('Paket Bento B - Rp25.000\n');
totalBill += parseInt(25000);
break;
case 3:
arrayCart.push('Paket Bento C - Rp30.000\n');
totalBill += parseInt(30000);
break;
}
break;
// and the 1st problem ends here
// This is to check the Cart's content
case 2:
// And I think the 2nd problem starts here
inputKeranjang = alert('Isi Keranjang Anda\n' + arrayCart + '\n\n' + 'Total Tagihan Anda: \n' + totalBIll)
break;
// and it ends here
//----------- everything under this line seems to be working fine ---------------------------------------
// This is to input how much money you would like to pay with and calculate the change or deficit (if any)
case 3:
inputPayment = parseInt(prompt('Total Tagihan Anda :\nRp' + totalBill + '\n\nBerapa uang yang Anda akan bayarkan?'));
switch(true)
{
case inputPayment<totalBill:
alert('Uang Anda kurang sebesar Rp ' + parseInt(totalBill-inputPayment));
break;
case inputPayment>totalBill:
alert('Anda akan mendapat kembalian sebesar Rp' + parseInt(inputPayment-totalBill));
break;
case inputPayment=totalBill:
alert('Uang Anda pas');
break;
}
break;
}
// This is to end the infinite loop and close the app
if(userInput === 4)
{
break;
}
}
I'm not the javascript developer but as far switch statement goes,
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
So whatever you pass as input to the switch("YouInput") it checks for that in all cases, so If you pass Int as your Input in first switch, let say 1 then case 1: will execute if you pass 100 case 100: if no case match default will and if you pass String let say "Yosia" then if there is any case "Yosia": that will execute
So in your second switch cases you are checking for case 1: , case:2 but I don't think your "inputPesanan" is of type int beacuse in everywhere else you are using some parseIn but not there so may be print and check you "inputPesanan" it will not be 1, 2, or cases you are looking for.

Javascript using a switch statement with `case x` for a wide range of numerical values x

I wish to use case within a switch switch statement like so:
case 'transfer' + amount:
sql.get(`SELECT * FROM scores WHERE userId ="${userID}"`).then(row => {
sql.run(`UPDATE scores SET points = ${row.points - amount} WHERE userId = ${userID}`);
bot.sendMessage({
to:channelID,
message: `You have transferred ` + amount + ` points. You currently have ${row.points} points.`
})
break;
If it sees transfer10 I want the code to take that value 10 to be amount however I have no idea how to do that.
Thanks in advance :)
I do not think you can create switch statement with dynamic-generated case statements. I also do not see any real advantage of doing this, plus the logic behind this it would be hard to understand from anyone else who will be reading the code.
What about using the switch statement do determine the art of action and accessing the _amount_in the case statements ?
var amount, action;
// some code
...
amount = 2;
// some code
...
action = 'transfer' // or delete, update ...
// some code
...
switch(action) {
case 'transfer':
// do some SQL and access the amount
...
break;
case 'delete':
// do some SQL and access the amount
break;
default:
// some default action
}
If you really need something like a dynamically-created switch-statement look at the first answer from this question.

Why is the rest of my JS code not letting my JQuery run?

apologies for the basic question but I'm just starting to learn JS. I'm trying to build a blackjack game, and I started off in my .js file by creating a constructor function (for the cards) and then I defined one of the methods in that function. Here is the code in my .js file (I've not shown what's inside the actual cardToString function as it's about 70 lines long):
EDIT: Some people have asked I include the entire code, so here it is:
function Card(rank, suit) {
this.rank = rank;
this.suit = suit;
this.toString = cardToString;
this.createNode = cardCreateNode;
}
function cardToString() {
var rank;
var suit;
switch (this.rank) {
case "A" :
rank = "Ace";
break;
case "2" :
rank = "Two";
break;
case "3" :
rank = "Three";
break;
case "4" :
rank = "Four";
break;
case "5" :
rank = "Five";
break;
case "6" :
rank = "Six";
break;
case "7" :
rank = "Seven";
break;
case "8" :
rank = "Eight";
break;
case "9" :
rank = "Nine";
break;
case "10" :
rank = "Ten";
break;
case "J" :
rank = "Jack";
break;
case "Q" :
rank = "Queen";
break;
case "K" :
rank = "King";
break;
default :
rank = null;
break;
}
switch (this.suit) {
case "C" :
suit = "Clubs";
break;
case "D" :
suit = "Diamonds";
break;
case "H" :
suit = "Hearts";
break;
case "S" :
suit = "Spades";
break;
default :
suit = nill;
break;
}
if (rank == null || suit == null)
return "";
else
return rank + " of " suit;
}
$(document).ready(function() {
$("#deal").click(function() {
$("#hit").fadeOut('slow');
});
});
I'm completely confused, because when I put this into the .js file the jQuery doesn't work, however when I comment out everything but the jQuery it works fine. I'm sure it's something basic that I'm just not aware of, but I've searched for a while and can't find an answer. Basically, I have no idea why my first few bits of JS stop the jQuery from working.
EDIT: Someone asked me if I checked the console for errors, and sure enough I do get one:
Uncaught SyntaxError: Unexpected identifier
Next to this it said "jsjquery.js:4" and I think 4 refers to the line of code which was an empty line right at the beginning (I have some comments on the first few lines, then left a line before I starting coding). I removed empty line, now it says the error is on line 80, which is this piece of code:
return rank + " of " suit;
This error goes away when I comment out everything but the jQuery.
This might make everything clear to you guys, but I'm still lost!
Thanks.
EDIT: Ok final edit I promise, haha. For anyone who might come across this question looking for an answer: I made a couple of syntax mistakes, but the real problem was that I didn't define the method cardCreateNode. I didn't realise that not doing so would cause everything else to not run. Thank you to everyone who responded!
default :
suit = nill;
break;
unexpected identifier is syntax error. Obviously you mean null here, not nill.
Since you have a different error based on the update of your post I'll answer your latest issue being that you receive an error on this line:
return rank + " of " suit;
You are missing the concatenation on the other side of " of " so it should look like this:
return rank + " of " + suit;
Also in your switch statement you have this line:
default :
suit = nill;
break;
I think here you mean to set the value to null not nill which would look like this:
default :
suit = null;
break;

SyntaxError: Unexpected token case?

There are five cases that are accepted. Still kind of a newbie to Java, so this is a slightly odd case. As far as I can tell (I've read the code at least twice) it should work perfectly fine, unless the double switch is making it not function... I get the error "SyntaxError: Unexpected token case"
var shouldWeapon = String("sword");
var user = prompt("There's a duck in a pond. It likes fish. What do you do? Would you like to feed it, kill it, skin it, buy it, or fight it").toLowerCase();
switch(user) {
case 'feed it':
var whatHaveFood = prompt("What do you have for food?").toLowerCase();
switch(whatHaveFood) {
case 'pancakes':
console.log("Great! Ducks love their pancakes!");
break;
case 'muffins':
console.log("I'm sorry what? You carry muffins? Ducks LOOOOOOOOOOOVE MUFFINS LIKE OMIGOSH I LOVE MUFFINS MMMM M M MMMM MMM IN MY TUMMY.");
break;
case 'dormant spiders':
console.log("You decide not to give them to the duck. They're yours. Nobody gets your dormant spiders.");
break;
case 'apple':
console.log("OH BOY I LOVE APPLES -said no duck ever.");
break;
default:
console.log("The Duck doesn't like that. He curses you to the pits of hell and walks away.");
break;
};
break;
case 'kill it':
var whatHaveWeapon = prompt("What sort of weapon do you have?").toLowerCase();
if(shouldWeapon || whatHaveWeapon){
console.log("Why Aren't you using a sword? Why are you using a " + String(whatHaveWeapon) + ". They Suck!");
}else{
console.log("Good choice. The Duck is vanquished.");
}
break;
case 'skin it':
var tempCat = prompt("What temperature is the cat?");
if(tempcat > 4){
console.log("Don't skin ducks.");
}
else{
console.log("That's a freaking cold cat.");
}
break;
case 'buy it':
var buyDuckCost = Math.floor(Math.random()*5 + 1);
var buyDucky = ("How much money do you have?");
var missingMoney = buyDuckCost - buyDucky;
if(buyDucky >= buyDuckCost){
console.log("You have bought a duck! congratulations!");
}
else{
console.log("I'm sorry you don't have that much money. You still need" + String(missingMoney) + "$! The duck pulls out a gun and shoots you.");
break;
case 'fight it':
var Smickle = true
var Donkey = false
if(Donkey || Smickle){
console.log("YOU CAN'T FIGHT THE DUCK. THE DUCK IS TOO STRONG");
}
else{
console.log("Ummmm... this is the only accessible answer..... OMEGA GOOD JOB*Cute anime loli voice.*")
}
break;
console.log("What? You're going to do what with the duck?")
default:
}
As far as I know, this should function....
In this part ("buy it" case), you are missing this end brace.
else {
console.log("I'm sorry you don't have that much money. You still need" + String(missingMoney) + "$! The duck pulls out a gun and shoots you.");
} //<<-- missing this end brace
break;
Code working here

Categories

Resources