How to create an online quiz or assessment test using SurveyJS and add scoring and timing to it (Part 2)
Tags: form, javascript, scoring, surveys
Published: 2023-03-07 14:49:27

![Add scoring to a survey, quiz, or test - SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqbgjb7ky7zcmtmva5q8.png)

## Survey Creator to Save the Day

Writing a few dozen lines in JSON to configure a 3-question geography quiz isn't a big deal. But what if it is a multi-page assessment test or several of them? Then, manual coding is simply not an option, especially if there are other ways to create such complex tests (!) without a developer involved.

We are talking about [Survey Creator](https://surveyjs.io/survey-creator), an embeddable GUI-based form builder that allows you to have a self-hosted tool for creating, storing, and analyzing any educational assessment materials. Whether it is a pop quiz at the end of a class or a midterm exam - your end users, e.g., teachers, can configure the contents and appearance of such forms easily.

### Auto-generate the form model in JSON

To demonstrate the functionally of Survey Creator, let's head over to its [free full scale demo](https://surveyjs.io/create-free-survey). Drop a radio button group question from the toolbox on the left onto the design surface to create a form.

![Free Survey Tool UI - SurveyJS | Adding a radio button group question](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4sg3p1j6d6ppsxcug1l8.png)

Then, add a title, description, and assign values to the first question (“How many continents are there?” with four choice options: 4, 6, 5, and 7) to turn this form into our sample **Geography test**. The folded tabs on the right make up the Property grid, where users can change the question, [panel](https://surveyjs.io/form-library/documentation/api-reference/panel-model), and form settings.

We will not focus on the basic functionality of the Survey Creator interface this time. Please refer to the [dedicated end-user guide for Survey Creator](https://surveyjs.io/survey-creator/documentation/end-user-guide) for details.

![The Property grid of the Survey Creator UI — SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltx522xx8413pkpsc0ns.png)

### Set the Correct Answer for a Question

The default functionality of the Property Grid allows you to set a correct answer for a question. To do this, switch to the question settings level, click the Set Correct Answer button under Data, and select the right answer in the Correct Answer popup, then click Apply.

![How to set the correct answer for a question — SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/swmdyflvie7re2avivop.png)

Let’s add a few more questions to our test and move on to setting up timing. As we can include any question type supported by the SurveyJS Form Library, let’s add a dropdown menu to the same page and another radio button group to the second one.

![Add a Single Selection Dropdown menu to a test — SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lamxub1sa8d5c5v47c1w.png)

### Setup time limits in Survey Creator UI

To specify time limit, select survey-level settings, and under the Timer/Quiz section of the Property Grid, enter the number of seconds you want to allow for each page and/or for the entire survey to complete. You can also configure the time visibility and position to make sure students can self-pace to answer all questions.

![How to time a test in Survey Creator UI — SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ky35e3v8zuer5jf1xt25.png)

### The Survey Complete section

Like most other form settings, customized feedback pages can also be configured in the graphical interface of Survey Creator. If you only want to calculate scores by comparing choices with the predefined correct answers, then at the survey level setting, select the Survey Complete section and enter the rule in the Survey Complete markup using markup tags.

![Configure a custom test result page — SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqyfnkao6yl8a0pf3bzp.png)

In order to display a personalized feedback based on the number of correct answers a student provided, in the same section of the Property Grid add a Dynamic Survey Complete page markup and specify an expression that triggers it as shown in the example below:

![Create a dynamic test result page — SurveyJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hbr623orfxe92p53entd.png)


## What's scoring?

Scoring is the process of evaluating or assigning a numerical value or score to a particular question of a test, exam, quiz, or other assessment form or to a single-choice option of such a question. It involves applying rules or criteria to assess the quality, quantity, or level of performance of the question or item being scored.

Scoring has various fields of application, including academic or professional settings, sports, games, or contests. In education, for example, scoring is used to assess knowledge, skills, or abilities of students in a particular subject or course. Scores can be used to compare students’ performance, determine grades or rankings, or provide feedback for improvement. In the banking sector, scoring can help evaluate loan applicants based on their answers and sort out trustworthy ones.

### How to Add a Scoring to a SurveyJS Form

1.1 By default, the Property Grid doesn’t include a `score` property. 
To [add a custom property to the Property Grid](https://surveyjs.io/survey-creator/documentation/property-grid#add-custom-properties-to-the-property-grid), we need to call the `addProperty(questionType, propertySettings)` method on the `Survey.Serializer` object. The only difference between adding a custom `score` property to a question and to a choice option is the class you add it to. Since only a single answer is correct in a [scored quiz](https://surveyjs.io/form-library/examples/create-a-scored-quiz/reactjs), a score property is added to a [Question](https://surveyjs.io/form-library/documentation/api-reference/question) class. On the contrary, there are no correct answers in a [scored survey](https://surveyjs.io/form-library/examples/create-a-scored-survey/reactjs), so a custom `score` property needs to be added to the `ItemValue` class. Compare the following code:

* To add a custom `score` property to questions:
```
import { Serializer } from “survey-core”;

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

* To add a custom `score` property to choice options:
```
import { Serializer } from “survey-core”;

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

1.2 Now when the score property is serialized and included in the survey JSON schema, you need to assign its values for each question, the same way we specified the `correctAnswer` property earlier. Here is how the first question of our sample test looks like with both properties configured:

```
{
  "type": "radiogroup",
  "name": "count_continents",
  "score": 5,
  "title": "How many continents are there?",
  "correctAnswer": "Item 7",
  "choices": [
    "4",
    "6",
    "5",
    "7"
  ],
  "colCount": 2
}
```


### Calculate the Total Score

1.3 To sum up the total score, you need to handle the [onComplete](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#onComplete) event and use the following `calculateTotalScore` helper function with a question’s [isAnswerCorrect](https://surveyjs.io/form-library/documentation/api-reference/question#isAnswerCorrect) method, which checks if the question was answered correctly.

```
function calculateTotalScore (data) {
  var totalScore = 0;
  Object.keys(data).forEach((qName) => {
    const question = survey.getQuestionByValueName(qName);
    if (question.isAnswerCorrect()) {
      if (!!question.score) {
        totalScore += question.score;
      }
    }
  });
  return totalScore;
}
```
Refer to this [free demo showing how to configure a scored quiz](https://surveyjs.io/form-library/examples/create-a-scored-quiz/reactjs) to learn how to calculate the maximum score with the `calculateMaxScore` helper function.

1.4 Finally, once the total score has been calculated, we need to modify the [completedHtmlOnCondition](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model#completedHtmlOnCondition) array by using different placeholders in the expression property that triggers a custom markup. Since we don’t simply count correct or incorrect answers but points assigned to each correct answer, the arguments change to `{totalScore}` or `{maxScore}` etc. Here is an example:

```
const surveyJson = {
  ...
  completedHtmlOnCondition: [{
    expression: "{totalScore} > 10",
    html: "<h4>Congratulations! You got {totalScore} points and passed the test. Well done!</h4>"
  }]
};

```


## A Basic Geography Test Demo

You can now see our basic Geography Test built with Survey Creator in action. Click “Open Sandbox” to run free demo:

{% embed https://codesandbox.io/embed/laughing-lumiere-yvnmg8?fontsize=14&hidenavigation=1&theme=dark&view=preview %}


## Conclusion

SurveyJS offers a wide range of built-in features for online tests and quizzes, including timing, scoring, a custom feedback or [start page](https://surveyjs.io/form-library/documentation/design-survey/create-a-quiz#set-up-a-start-page), and more. You can manually write a form model in JSON (please consult with the [Form Library API references](https://surveyjs.io/form-library/documentation/api-reference/survey-data-model)), run it for free in your app, and [store the results in your own database](https://surveyjs.io/form-library/documentation/handle-survey-results-store).

However, if the complexity and number of assessment forms you deal with are significant, you might want to leverage the drag-and-drop UI of Survey Creator - a self-hosted form builder tool, which ships with a [free full scale demo](https://surveyjs.io/survey-creator). Once added to your application, Survey Creator auto-generates a form model for you while your end users configure the contents and layout of a form in a no-code UI. The generated form is then stored and loaded from your database in the same JSON format and is rendered in your app.

The Creator UI is fully customizable, you can tailor it to the needs of your end users to make it even more pleasant and easy to work with. [Add](https://surveyjs.io/survey-creator/examples/add-properties-to-property-grid/reactjs), [remove](https://surveyjs.io/survey-creator/examples/removeproperties/reactjs) or [hide properties](https://surveyjs.io/survey-creator/examples/hide-category-from-property-grid/reactjs) of survey elements in the Property Grid, modify visibility of default tabs or add your custom tabs or buttons — you name it.

With SurveyJS it’s never been easier to create, modify and run scored tests and surveys. Select your preferred frontend technology and [get started](https://surveyjs.io/form-library/documentation/get-started) with your first Survey JS assessment form today!