The process of obtaining points through accurate responses using form inputs

My task is to create a unique quiz consisting of 10 questions. Half of the questions are multiple choice, which require radio inputs, while the other half are written answers that need text inputs. To ensure accuracy and provide a scoring system, I came across a helpful script on stack overflow that can keep track of scores as users enter their answers.

For the multiple-choice questions, I have implemented the following script:

$(document).ready(function(){ 
  $('input[name=radio1]').change(function(){
     $('.alert').remove();
    if($('input[name=radio1]:checked').val() === "1") {
      $(this).parent().append('<span class="correct">✓ Correct!</span>');
    } else {
      $(this).parent().append('<span class="incorrect">✗ Correct answer = B</span>');
    }
  });
});

Here, the correct answer is indicated by value="1", while the incorrect options have value="0".

As for the written answers, I use the following script:

$('submit').on('click', function() {
    markAnswers(1)
});

var answers = {
  q1: ["Auto's"]
};

function markAnswers(id) {
  $(`#q${id}`).each(function () {

    let userAnswer = this.value.replace(/[^\w\'\,\-\?\!\"\:\—\;]/g,'');

    if ($.inArray(userAnswer, answers[this.id]) === -1) {
      $(this).parent().append(`<br><span class='incorrect'>✗ Correct answer = ${answers[this.id]}</span>`);
    } else {
      $(this).parent().append("<br><span class='correct'>✓ Correct!</span>");
    }
  });
}

The correct value for the written answers is determined by this script.

Now, I found another interesting script that tracks the score using data-score=. However, I am considering using value instead. The original script is provided below:

$('.track').change(function(e) {
    update_progress();
});

// supports any number of inputs and calculates done as %

function update_progress() {
    var score = 0
    $('input.track').each(function(){
      var _score = $(this).data("score")
        if ($(this).val().length > 0) {
          score += _score
        }
      })
  $('#score').text(score)
    var count = $('.track').length;
    var length = $('.track').filter(function() {
    return this.value;
}).length;
    var done = Math.floor(length * (100 / count));
    $('.perc').text(done);
    $('.meter').width(done + ""%");
} 

You can find the script here: . It's a useful script that not only keeps track of scores but also indicates whether the form has been completed or not.

In my quiz, I would like each correct answer to have a value of 1. This way, users can achieve a maximum score of 10/10 at the end. However, I am unsure how to implement this and would appreciate any suggestions or solutions from you guys. Thank you!

Answer №1

You could approach it in this way, although it's generally recommended to avoid using globally accessible variables. However, for the sake of simplicity, I have included them here. It would be better to wrap everything in a div and store the score/progress as data attributes.

Here is an example on CodePen: https://codepen.io/lenadax/pen/QWQqMxP?editors=1111

// global vars, put them somewhere else
var progress = 0;
var score = 0;

$('form.question').each(function(i, el) {
  // I'm lazy so form id is the same as input name for each question
  let inputs = $(`input[name=${$(this).attr('id')}]`);

  inputs.on('change', function() {
    // increase progress by 1 if button has been selected.
    progress++;
    if ($(this).val() === "1") {
        // increase score if correct choice selected
        score++;
        $('<span class="result correct">').text('✓ Correct!').appendTo(el);
    } else {
        $('<span class="result incorrect">').text('X Incorrect!').appendTo(el);
    }
    // get number of questions
    let questionCount = $('form.question').length;
    // disable after choosing for less hassle
    inputs.prop('disabled', true);
    
    // calculate the progress in percent
    let progressNum = progress / questionCount * 100;
    $('.perc').text(progressNum);
    $('#score').text(`${score} / ${questionCount}`);
   });
})
input {
  display: inline-block;
}

label {
  display: inline-block;
}

button {
  display: block;
}

form {
  width: 200px;
  border: 1px solid gray;
  margin: 10px;
  padding:10px 5px;
}

.result {
  display: block;
}

.result.incorrect {
  color: red;
}

.result.correct {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
 <body>
  <form class="question" id="question1">
    <span>Question 1</span>
    </p>
    <input name="question1" id="answer1" type="radio" value="0"/>
    <label for="answer1">Wrong answer</label>
    </p>
    <input name="question1" id="answer2" type="radio" value="1"/>
    <label for="answer2">Right answer</label>
  </form>
  <form class="question" id="question2">
    <span>Question 2</span>
    </p>
    <input name="question2" id="answer1" type="radio" value="0"/>
    <label for="answer1">Wrong answer</label>
    </p>
     <input name="question2" id="answer2" type="radio" value="0"/>
    <label for="answer2">Wrong answer</label>
    </p>
    <input name="question2" id="answer3" type="radio" value="1"/>
    <label for="answer3">Right answer</label>
  </form>
  <h5>Done <span class='perc'>0</span>%</h5>
  <h5>Score <span id="score">0</span></h5>
 </body>
</html>

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

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

Set up global variables for components to access

Currently, I am working on a Laravel 8 project with vue-sweetalert2 integration. My goal is to set up the Toast behavior once and then be able to call it within various components. At the moment, my code looks like this: /js/components/Mypage.vue <scr ...

Tips for managing a PHP post request without full knowledge of the variables to retrieve

My form allows users to dynamically add new lines using JavaScript. However, when they click the save button, I am struggling to capture and assign the new data to a variable. The current issue is that once the user adds new rows and clicks save, the rows ...

reverting the effects of a javascript animation

I am expanding the size of a carousel on a specific pane by adjusting its height and position. Here is how I achieve this: if(currentPane==2) { $("#carousel").animate({height:320},1000); $("#carousel").animate({top:411},1000); $("#dropShadow") ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Restrict the number of rows in a real-time search JSON data by utilizing the $.each method

Is there a way to limit the number of rows returned in live search JSON data through URL? I attempted to count the table rows and return false, but it did not work. Any suggestions on how to achieve this? $(document).ready(function() { $.ajaxSetup ...

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

What is the most effective method for handling extremely large Long numbers in Ajax?

When it comes to Javascript, all numbers are represented as double-precision floating-point. This can result in a loss of precision when handling numbers that exceed the 64 bit Java Long datatype limit of 17 digits. For instance, a number like: 7143412520 ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

Error: The JavaScript variable 'undefined' is being used as a function, which is incorrect. This error occurs when trying to execute the function `mockBackend

I am currently working on unit testing an AngularJS controller using Karma and Jasmine. Below is the test suite I have created: describe('Controllers', function(){ var $scope, ctrl; beforeEach(module('curriculumModule')); ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

Encountering the "ERR_FILE_NOT_FOUND" message within the popup of my Chrome extension

Currently, my manifest file is structured as follows: { "manifest_version": 2, "name": "My Extension", "description": "A starting point for creating a functional Chrome extension", "version": "0.0.1", "browser_action": { "default_popup": " ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

Styling Your Navigation Bar with CSS and Active States

Creating an interactive navigation element for a menu can be challenging, but here's a helpful example. http://jsfiddle.net/6nEB6/38/ <ul> <li><a href="" title="Home">Home</a></li> <li class="activ ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

The Protractor Custom Locator is experiencing difficulty in finding the element

For our project, the automation team is incorporating a custom attribute called 'lid' to elements where unique identification is challenging. A new custom locator method has been developed to find elements using the 'lid' attribute: ...

Read and manipulate website content using PHP

I recently encountered a challenging situation as a newcomer. Despite searching on Google, I couldn't find any information about it. There is a website that allows users to search for doctors in their area or state. It's possible that the number ...