Home > Enterprise >  Need help adding up a score from correct answers taken from <input> in javascript
Need help adding up a score from correct answers taken from <input> in javascript

Time:01-28

I'm new to programming and I made a sort of quiz thingy that has 10 input areas on a page. Using javascript I want to be able to verify the typed answer and give a point for correct and no point for incorrect.

html:

<div>
        <h1>Postal knowledge test. Write all the answers in lowercase, no spaces!</h1><br><br>
        <h5>Who do you play as in Postal 2?</h5><br>
        <input type="text" id="maincharacter"><br>
        <h5>Who is the voice actor for the character you play as?</h5><br>
        <input type="text" id="voiceactor"><br>
        <h5>How many days are there in Postal 2?</h5><br>
        <input type="number" id="days"><br>
        <h5>What do you need to retrieve from the Factory?</h5><br>
        <input type="text" id="factory"><br>
        <h5>On what day do you need to piss on your dads grave?</h5><br>
        <input type="text" id="dadgrave"><br>
        <h5>What weapon spawns in the shed in front of you on Monday?</h5><br>
        <input type="text" id="weapon"><br>
        <h5>What female animal is the wife named after?</h5><br>
        <input type="text" id="wife"><br>
        <h5>What's uncles name?</h5><br>
        <input type="text" id="uncle"><br>
        <h5>What item gives you 125 health?</h5><br>
        <input type="text" id="health"><br>
        <h5>How many official Postal games are there?</h5><br>
        <input type="number" id="games"><br><br>
        <button id="checkanswers" type="button" onclick="answer()">Check how many questions you got correct</button><br>
        <h5 id="answer"></h5>
    </div>

javascript:

function answer() {
                const q1 = document.getElementById("maincharacter");
                let qq1 = q1.value;
                const q2 = document.getElementById("voiceactor");
                let qq2 = q1.value;
                const q3 = document.getElementById("days");
                let qq3 = q1.valueAsNumber;
                const q4 = document.getElementById("factory");
                let qq4 = q1.value;
                const q5 = document.getElementById("dadgrave");
                let qq5 = q1.value;
                const q6 = document.getElementById("weapon");
                let qq6 = q1.value;
                const q7 = document.getElementById("wife");
                let qq7 = q1.value;
                const q8 = document.getElementById("uncle");
                let qq8 = q1.value;
                const q9 = document.getElementById("health");
                let qq9 = q1.value;
                const q10 = document.getElementById("games");
                let qq10 = q1.valueAsNumber;
            }

What my original plan was, was to check the answer using an if statement i.e.:

//first question checker
var p1;

if (qq1 == "postaldude") {
    p1 = 1;
}
else {
    p1 = 0;
}

document.getElementById("answer").innerHTML = p1;

p1 being given the value 1 or 0 depending if the answer is correct or not, then being added up with the other question results in the innerHTML i.e.: p1 p2 p3 p4 p5... ;

but this doesn't work as you can't have more than 1 if statement, so if I try to add more of these it simply doesn't work. I tried using else if but I can't get it to work.

I am unsure if there is a way to what I'm trying to do work or if there is a fully different method of doing it. Sorry if my code is very basic, this is what I've learned so far. Anyhow any tips or explanation would be greatly appreciated, Thanks!

What I tried:

I tried adding 10 if else statements for each question i.e.:

if (...) {
    ...;
}
else {
    ...;
}
if (...) {
    ...;
}
else {
    ...;
}
if (...) {
    ...;
}
else {
    ...;
}
if (...) {
    ...;
}
else {
    ...;
}
...

but unsurprisingly that didn't work. I also tried doing what I did above but making them all 'else if' but that didn't work either.

CodePudding user response:

Hi

There is no problem in adding multiple if statements, but you can do the same in a scalable way.

  1. Save question input ids and answers in an object (you can use Map also)
const idAnswersMap = {
"maincharacter": "postaldude",
"voiceactor": "answer"
}
  1. checkout for-in loop for looping through objects
  2. get answer for each input, compare with actual answer and sum in the same loop
  3. Don't ever forget to name variables based on their use, it will help you afterwards big time.
let totalCorrect = 0;
for (let id in idAnswersMap) {
    // get answer for each input
    const answer = document.getElementById(id).value;
    if (answer === idAnswersMap[id]) {
      totalCorrect  ;
    }
}
  1. totalCorrect now holds what you need.

CodePudding user response:

First, add a class to each of the inputs so you can simplify the checking.

E.G <input type="text" id="maincharacter">

Now, javascript canlook like this. Where answer_sheet will have a key for each input matching the ID.

const questions = document.querySelectorAll(".question");

var answer_sheet = {
  "maincharacter": "postaldude"
};

function answer() {
    var score = 0;
    questions.forEach((question) => {

        if(!(question.id in answer_sheet)) return;

        var questionValue = question.value.toLowerCase();
        var answerValue = answer_sheet[question.id].toLowerCase();

        if(questionValue == answerValue) {
            score  ;
        }

    });
    alert("Score: "   score);
}

Please note that anyone can inspect the code on the page and see the answer sheet as given, so this isn't very secure.

To get around this, you would probably utilize a technology like Ajax to send a list of the answers the user provided to a separate PHP script to process the answers, but it's a bit out of scope of your question.

  • Related