What is the best method to incorporate the score based on the value using survey.js?

I'm currently working on a Quiz that involves assigning a score based on the chosen option. Then, at the end of the quiz, the total scores are calculated based on the selected options. Here is the code snippet I am using: Html. (library. survey.ko.js)

<div id="surveyElement"></div>
<div id="result"></div>

Js

var json = {
     "title": "Quiz",
     "description": "Quiz Test",
     "pages": [
      {
       "name": "page1",
       "elements": [
    {
     "type": "radiogroup",
     "name": "LifeStyleQ11E1",
     "title": "Do you smoke?",
     "isRequired": true,
     "choices": [
      {
       "value": "SmokeYes",
       "text": "Yes",
       "score": 5
      },
      {
       "value": "SmokeNo",
       "text": "No",
       "score": 4
      }
     ]
    }
   ],
       "title": "Introduction",
       "maxTimeToFinish": 2
      },
      {
       "name": "page2",
       "elements": [
        {
         "type": "radiogroup",
     "name": "LifeStyleQ10E1",
     "title": "Do you suffer from back pain?",
     "isRequired": true,
     "choices": [
      {
       "value": "BackPainYes",
       "text": "Yes",
       "score": -4
      },
      {
       "value": "BackPainNo",
       "text": "No",
       "score": 5 //This score needs to be added for each question.
      }
       ],
       "title": "Introduction"
      }};
    var survey = new Survey.Model(json);

survey.onComplete.add(function(result) {
    document.querySelector('#result').innerHTML = "result: " + JSON.stringify(result.data); 
});

My goal is to accumulate the scores when an option is selected, and keep adding them until the end of the quiz. I noticed that the JSON result only displays the "value" but not the "score" element. Any ideas on how to solve this issue?

Answer №1

This particular unit test extracted from the SurveyJS Library source code showcases precisely the scenario you are referring to - https://github.com/surveyjs/survey-library/blob/master/tests/surveytests.ts#L7266-L7594

QUnit.test(
  "custom fields in getPlainData - https://surveyjs.answerdesk.io/ticket/details/T1778",
  function (assert) {
    Serializer.addProperty("question", {
      name: "score:number",
    });

    Serializer.addProperty("itemvalue", {
      name: "score:number",
    });

    var q = new QuestionImagePickerModel(null);

    var survey = new SurveyModel({
      questions: [
        {
          type: "rating",
          name: "question11",
          score: 11,
        },
        // Other question objects here...
      ],
    });
    
    // Data assignments and calculations go here...

    var plainData = survey.getPlainData({
      calculations: [{ propertyName: "score" }],
    });
    // Assertions on the plain data structure go here...

    Serializer.removeProperty("question", "score");
    Serializer.removeProperty("itemvalue", "score");
  }
);

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

Measuring the number of distinct words within a given set of strings

Describing my attempt to create a function that processes string arrays by adding unique words to a word array, and incrementing the count of existing words in the count array: var words = []; var counts = []; calculate([a, b]); calculate([a, c]); funct ...

Iterate through JSON and dynamically populate data

My goal is to dynamically populate content by iterating through JSON data using jQuery. First, an Ajax request is made Then the data is looped through to create HTML tags dynamically A div container with the class "product-wrapper" is created for each J ...

Seeking assistance with setting up checkboxes to sort through elements in an array

As a beginner in the world of HTML, JavaScript, and CSS, I have a basic understanding of these languages. My current class project requires me to create checkboxes that can filter out content from an array based on the presence of a certain letter in the a ...

What is the best way to ensure form submissions in jQuery include non-empty inputs?

Is there a way to only send non-empty inputs (those with values not equal to "") when a user submits a form? I want to achieve this because my website offers forms for filtering data, using the GET method to indicate query strings in the URL. However, som ...

When a custom header is added, cookies are not included in cross-origin jQuery AJAX requests

An issue arises when sending an ajax request from our main domain to a subdomain (cross-origin) through jQuery. Despite having CORS implemented and functional, we encounter a problem when attempting to include a custom header in the request. The presence o ...

Outputting data stored in Firestore object

Is there a way to display the content of a Firestore object in Angular Firebase? I am working on a project where I need to retrieve and print the name of a document stored in Firestore. In my Firestore database, I have a parent collection called "nforms" w ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Refreshing a Datatable with an Ajax request: Step-by-step guide

I have a dynamic table that automatically updates with content from a model when the URL /project_page is accessed. Users can upload files on this page, and I want the table to refresh in real-time without requiring manual page reloads. To achieve this, ...

Calling functions by name in Java using JSON objects

Is it possible to invoke a function from a Java JSON object? For example: In Java: JSONObject json = new JSONObject(); json.put("fnRowCallback", "test()"); Using jQuery: $ (function () { "use strict"; function test() { alert('test ...

The vuex store does not activate in routed components

After setting up my vuex store and ensuring that everything is functioning properly, I encountered an issue where I can only commit mutations in components that are directly imported into src App.vue. For instance, the resetState function in Header.vue su ...

JavaScript function for exporting HTML table to Excel with the ability to choose the file name

My current challenge involves a function used to export HTML to Excel: function generateexcel(tableid) { var table= document.getElementById(tableid); var html = table.outerHTML; window.open('data:application/vnd.ms-excel,' + encodeURICompo ...

Tips for arranging cards in a stacked position: To create a visually

I'm currently developing a project using react typescript, and I need to showcase various projects in the form of cards. However, I would like these cards to be displayed in a stacked layout like this Here is the component for displaying the projects ...

I would appreciate your assistance with the hide button

Is there a way to hide a button after clicking on it? I would greatly appreciate your help! ...

Why does my JSON parser consume significantly more memory when utilizing the Streaming API?

My current code is parsing the whole file using jsonparse: ConcurrentHashMap<String, ValueClass<V>> space = new ConcurrentHashMap<String, ValueClass<V>> (); Map<String, ValueClass<V>> map = mapper.readValue(new FileRead ...

Strategies for formatting JSON object key value pairs to display on individual lines

In one of my components, I have a JSON object stored inside an object called "job". It currently renders as: job {"amount": " 12185","job": "GAPA","month": "JANUARY","year": "20 ...

The dialogue box fails to appear when accessed from the dropdown menu shadcn

I'm encountering an issue while using nextJS with shadcn. I am attempting to open a dialog from a dropdown menu, but instead of opening, it just closes the dropdown menu. My assumption is that I either need to utilize ref and states or position the al ...

I need help showing the JSON data from the API in my Go application

Currently, I am working with a small API that returns a JSON response containing a Todo object. I want to display this information in my Go web server. At the moment, all that is being shown is 'Todo', which is hard-coded. How can I replace this ...

The Reactstrap Input Module lacks a Value prop when using React ref

I have a react component that includes an input element like so: import React, { Component } from 'react'; import {Input } from 'reactstrap'; constructor(props) { super(props) this.test = React.createRef(); ...

evaluating arrays of bytes

Looking for advice on comparing two byte-arrays in Java that represent (possibly negative) numbers. Is there a better way to compare them other than converting them back to integers and doing the comparison? I'm concerned about cases where one array ...

The function string.charAt() is returning a value of 0

I'm attempting to output each letter of a word separately by using the variable string. Here is the code I have so far: function typewriter() { var el = document.getElementById("typewr"); var string = "Hello"; for(var i=0;i<string.le ...