"Implementing the use of 'if' statements to increment the score when matching an element in

Hey there, I'm still pretty new to JavaScript and finding W3 Schools a bit overwhelming. Could someone please guide me on how to increment the score by 1 if getanswer1 is equal to answer[0]?

I've watched countless tutorials on creating quizzes, but they all seem to skip over explaining the concepts behind the code. It's not very helpful at all.

HTML

<h2 id="numberofquestions"></h2>
<h3 id="q1"></h3>
        <form class="answers" name="question1form">
        <input type="radio" onclick = "getAnswers()" value="a" name="question1"><label class="pAnswers">a) .</label>
        <input type="radio" onclick = "getAnswers()" value="b" name="question1"><label class="pAnswers">b) .</label>
        <input type="radio" onclick = "getAnswers()" value="c" name="question1"><label class="pAnswers">c) .</label>
        <input type="radio" onclick = "getAnswers()" value="d" name="question1"><label class="pAnswers">d) .</label>
        </form>

<h3 id="q2"></h3>
    <form class="answers" name="question2form">
        <input type="radio" onclick = "getAnswers()" value="a" name="question2"><label class="pAnswers">a) .</label>
        <input type="radio" onclick = "getAnswers()" value="b" name="question2"><label class="pAnswers">b) .</label>
        <input type="radio" onclick = "getAnswers()" value="c" name="question2"><label class="pAnswers">c) .</label>
        <input type="radio" onclick = "getAnswers()" value="d" name="question2"><label class="pAnswers">d) .</label>
    </form>

Javascript

console.log("Yay, JS is linked and working!" +
" P.S. 42!");

var noOfQuestions = 10;
var score = 0;
var questions = ["question 1", "question 2", "question 3", "question 4", "question 5", "question 6", "question 7", "question 8", "question 9", "question 10"];
var answer = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b'];


document.getElementById('numberofquestions').innerHTML = ("This quiz consists of ") + noOfQuestions + (" questions. Please make sure to answer all of them.");

function displayQuestions() {

        document.getElementById('q1').innerHTML = questions[0];
        document.getElementById('q2').innerHTML = questions[1];
        document.getElementById('q3').innerHTML = questions[2];
        document.getElementById('q4').innerHTML = questions[3];
        document.getElementById('q5').innerHTML = questions[4];
        document.getElementById('q6').innerHTML = questions[5];
        document.getElementById('q7').innerHTML = questions[6];
        document.getElementById('q8').innerHTML = questions[7];
        document.getElementById('q9').innerHTML = questions[8];
        document.getElementById('q10').innerHTML = questions[9];

}

// If input equals answer [letter], then add to score

function getAnswers() {

        var getAnswer1 = document.getElementsByName('question1');
        var getAnswer2 = document.getElementsByName('question2');
        var getAnswer3 = document.getElementsByName('question3');
        var getAnswer4 = document.getElementsByName('question4');
        var getAnswer5 = document.getElementsByName('question5');


        if ( getAnswer1.radioValue ('a')) {
                // radio == answer[0] then ++1 score else do nothing
                // $.inArray( getAnswer1, [answer[0]] );

        }

}

Thank you for any assistance!

Answer №1

It appears that the primary focus of your inquiry is on obtaining the value of a radio input, which can be found in this resource: Get Radio Button Value with Javascript. The subsequent step involves comparing the retrieved value with the correct answer:

if (getRadioValue(getAnswer1) === answer[0]) {
    ++score;
}

If you were to encapsulate the solution provided in the above link within a function named getRadioValue(), it would resemble this structure:

function getRadioValue(radios) {
    for (var i = 0, length = radios.length; i < length; i++) {
        if (radios[i].checked) {
            return radios[i].value;
        }
    }
}

On a separate note: Upon reviewing your code, I recommend enhancing your understanding of fundamental programming concepts (such as loops) before delving deeper into the development of interactive forms.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Functionality of Javascript event not being triggered

I am struggling with the following PHP code snippet: <?php foreach($items in $item) : ?> <a class="btn">$item</a> <?php endforeach; ?> Additionally, I have this piece of JavaScript: $('.btn').click(function() { cons ...

Tips for creating AngularJS forms which display radio buttons and populate data from a JSON file

I'm having trouble displaying the json data correctly. How can I show the radio buttons from my json file (plunker demo)? Additionally, I want to validate the form when it is submitted. Here is the HTML code: <my-form ng-app="CreateApp" ng- ...

Is it necessary to make multiple calls following a successful AJAX request?

Here is an AJAX call I am setting up. The first step is to hit the endpoint dofirstthing.do. Once that is successful, the next step is to make another call with "param1" as the query parameter. Now, my question is - how can I make a third call with "param ...

Exploring the versatility of Twig through variable iteration

Here is the structure of my array: array['a'] = {x => 1, y => 2...} array['b'] = {x => 5, y => 7...} I want to loop through the array and access either 'a' or 'b' based on my choice. {% for i in main % ...

Sending a $.ajax post request transforming into a get

Struggling to understand the behavior of my jquery ajax request, I've hit a roadblock. function newContact() { $.ajax({ type: 'POST', contentType: 'application/json', // url: ...

Using a pointer to access elements in a 4-dimensional array in the C programming language

Having trouble declaring a pointer in my 4d array. The declaration is as follows: int matrix[7][4][5][5] = { {/* Section 1 */ { /* 1st */ {0,0,1,0,0}, {0,0,1,0,0}, {0,0,1,0,0}, {0,0,0,0,0}, {0,0,0,1,0} }, ...

Tips for maintaining the position of a camera in three.js while also keeping its rotation fixed on the origin

In three.js, I'm looking to dynamically adjust my camera's position while ensuring that its rotation automatically aligns with the world origin. For instance, if the camera is initially set at: camera.position.set(25,25,25) I aim to have the ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...

Retrieve the variable within a function that runs after the state has been updated

When working with setting the state in reactjs "sync", I make use of a callback method like this: myFunction(){ var array = []; for(var i = 0 ; i > 100; i++){ array[i] = i; } this.setState({ someValue: 999 }, () =& ...

The Kadane's algorithm is yielding an incorrect maximum sum subarray, but is providing the correct maximum sum

I have implemented the Kadane's algorithm in Python 2.7 to find the maximum subarray. While my code correctly calculates the maximum sum (stored in the variable MSS) for a given example list, it seems to be returning the wrong subarray. I'm not s ...

Organizing data in TypeScript

Is there a way to alphabetically sort this list of objects by name using TypeScript? "[{name:"Prasanna",age:"22",sex:"Male",Designation:"System Engineer",Location:"Chennai"}, {name:"Nithya",age:"21",sex:"Female",Designation:"System Engineer",Location ...

Input form and select form collide in conflict when the "Enter" key is activated

My search box includes input forms and a select form with various options. The issue arises when using the place autocomplete feature from Google Maps alongside the select form. When the enter key is pressed after entering a location in the autocomplete fi ...

Is it possible to resize the output image in Three.js post-processing?

My game tends to lose performance when I switch to fullscreen mode, but it runs smoothly when the screen is small. I'm wondering if there's a way to render the game in small screen mode first and then scale up the processed render. I'm goin ...

Managing multiple properties linked to a main component array in VueJS

I am facing a challenge with a list of components that I would like to make editable and replicate the state to the parent component. The list component is defined as: Vue.component("shortcuts", { props: { shortcuts: Array }, template: '... ...

Nivoslider fails to display images when loaded in dynamic ajax content for the first time

Working on a website using jQuery and Ajax, I encountered an issue. When a page loads dynamically for the first time (before images are cached), the images do not display. However, when I reload the ajax load function, the pictures suddenly appear. $("#ov ...

Encountering an error while attempting to add a new component instance in Vue through a button click

Just to start, I want to mention that there might be a more appropriate way to achieve what I'm trying to do. Essentially, I'm looking to dynamically add an instance of a Vue component when a user clicks a button to expand it. I came across this ...

Modify the way text is selected in Windows

Can the text selection method in Windows be customized? If so, how can it be done? For instance, I am utilizing Mozilla Pdf.js on my website () Is it feasible to integrate a text selection feature similar to "Android", enabling users to edit the selected ...

Retrieve JSON information and convert it into arrays

I am looking to extract data from the following URL ( ) and organize it into 4 separate arrays: one for names, one for image URLs, and another for descriptions. The desired structure is as follows: nameArray = ['Lighting','Accessibility&a ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Smoother transitions with spline curves in Three.js

My current project involves drawing a CubicBezierCurve3 curve in three js. However, I want to enhance the drawing process by visualizing it as a moving rocket leaving behind a gas trail. Rather than having the entire curve drawn at once, I aim to draw it p ...