> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Create a Quiz

## Article: Create a Quiz

## Article Link: https://dev.wix.com/docs/coding-examples/extend-functionality/data/create-a-quiz.md

## Article Content:

# Create a Quiz

Generate a random quiz from a given set of questions. 

<div style="display: flex; flex-direction: row; align-items: center;"> 
<span style="display: flex; flex-direction: row; align-items: center; margin-right: 20px;"> 
<img src="https://wixmp-833713b177cebf373f611808.wixmp.com/images/08d72650aa29b51886430ccb4db77bd8.png" style="width: 15px; height: 15px;"> 
<span style="margin-left:3px; color:rgb(51 56 83); font-size:1rem">Intermediate</span> 
</span> 
<span style="color:rgb(51 56 83); font-size:1rem">Last updated: 14 Apr 2025</span> 
</div> 
<div style="display: flex; flex-direction: column; padding-top: 20px; padding-bottom: 20px;">
<div style="width: 100%; margin-bottom: 20px;"> 
<img src="https://static.wixstatic.com/media/d2a594_e3dfe7b101fb49179cc618bda709e8f1~mv2.png" alt="Create a Quiz" style="width: 100%;"> 
</div> 
<div style="display: flex; flex-direction: row; justify-content: space-between; align-items: center; width: 100%;">
<div style="margin: 0px 20px 20px 0px;">
<a href="fallback::https://manage.wix.com/edit-template/from?originTemplateId=8650d9ad-6149-42f1-8351-ef75f02e53ab&templateId=4a68e2f8-31b8-439e-9a32-5200ce18db19&autoDevMode=true" target="_blank"> <button style="margin-right: 10px;background-color:#106DFF; color:white; padding:10px 20px; border:none; border-radius:21px; cursor:pointer; margin: 0px 20px 20px 0px;" target="_blank">Open Example</button></a> 
<a href="fallback::https://www.wix.com/velo-examples/create-quiz" target="_blank"><button style="background-color:white; color:#106DFF; padding:10px 20px; border:1px solid #106DFF; border-radius:21px; cursor:pointer; width:125px;" target="_blank">Preview</button></a> 
</div> 
</div> 
</div> 
</div>

## About
---

In this example, we create a quiz that randomly selects 5 questions from a collection. Once a visitor answers and submits the quiz, we validate the answers and display the correct answer for each question along with the total score. 

## APIs 
---
<ul> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::repeater/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/repeater/introduction".md target="_blank">$w.Repeater API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::text-input/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/text-input/introduction".md target="_blank">$w.TextInput API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::radio-button-group/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/radio-button-group/introduction".md target="_blank">$w.RadioButtonGroup API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::button/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/button/introduction".md target="_blank">$w.Button API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::section/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/section/introduction".md target="_blank">$w.Section API</a></li> 
<li><a href="portalId::f356b938-ca2c-46f4-a390-e7ed146e00e0resourceId::4226f67a-73d7-47fd-acd0-e8e474f9f390slug::box/introduction*fallback::https://dev.wix.com/docs/velo/api-reference/$w/box/introduction".md target="_blank">$w.Box API</a></li> 
<li><a href="portalId::b85dea5b-341b-493b-b99e-4d4ca12baaa2resourceId::e8ae0bc0-16dc-4f95-b66e-c64d2998fcf7slug::introduction*fallback::https://dev.wix.com/docs/sdk/backend-modules/data/items/introduction".md target="_blank">Data - Items </a></li> 
</ul> 

## How we built it 
---
We added the following to our site:

#### Page Elements


##### Home Page
    
* A repeater for displaying quiz questions and answers. 
* Buttons to open the quiz and submit quiz answers.
* Text to display the total score. 

#### Collections
Questions: A collection containing the quiz questions, the type of input for each question, the possible options for multiple choice questions, and the correct answer to each question. 

#### Frontend Code 

##### Home

The code in this file initializes the page’s initial state, retrieves quiz data from the backend, and displays the quiz questions and answers. 

In this file, we: 
* Initialize the page elements and set the page’s initial display state. 
* Create multiple page displays and update them based on which button is clicked. 
* Retrieve quiz data by calling a backend function upon the start of the quiz.
* Render quiz questions, input options, and correct answers using a repeater.
* Validate visitor-submitted answers when the submit button is clicked.
* Calculate and display the total quiz score. 

#### Backend Code

##### questions.web.js

The code in this file retrieves the quiz questions at random from the questions collection.

We defined the following methods:
* `getRandomQuestions()`: Calls the other method to retrieve the quiz items and creates an array of quiz items at random. 
* `getAllQuestions()`: Retrieves all the quiz items.


## Code Snippets
---
<details open> 
<summary> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 18" width="22" height="22">
    <path d="M16.003 15.18c0 .57-.11 1.01-.31 1.32.2.31.31.75.31 1.32 0 .94.33 1.22.53 1.24.27.02.481.25.471.52-.01.27-.22.48-.49.48-.521 0-1.512-.47-1.512-2.24 0-.51-.1-.74-.16-.81h-.06c-.06 0-.11 0-.16-.01a.505.505 0 0 1-.561-.29.522.522 0 0 1-.04-.21c0-.08 0-.17.04-.25.1-.22.35-.32.58-.27h.2c.06-.06.17-.29.17-.81 0-1.77.992-2.24 1.513-2.24.28 0 .5.22.5.5s-.22.5-.5.5c-.18.02-.511.3-.511 1.24l-.01.01Zm5.967 1.1c-.09-.22-.33-.33-.57-.28h-.211c-.06-.06-.17-.29-.17-.81 0-1.77-.991-2.24-1.512-2.24-.27 0-.48.21-.49.48-.01.27.2.5.47.52.2.02.53.3.53 1.24 0 .57.11 1.01.311 1.32-.2.31-.31.75-.31 1.32 0 .94-.33 1.22-.511 1.24-.28 0-.5.22-.5.5s.22.5.5.5c.52 0 1.512-.47 1.512-2.24 0-.51.1-.74.16-.81h.06c.06 0 .11 0 .15-.01.23.06.47-.05.57-.27.041-.08.041-.17.041-.25 0-.07 0-.14-.04-.21h.01ZM17.014 4H6.001C5.451 4 5 4.45 5 5v14c0 .55.45 1 1.001 1h7.008v-1H6.001V5h11.013v6h1.001V5c0-.55-.45-1-1-1Zm-9.01 7h7.008v-1H8.004v1Zm7.008-4H8.004v1h7.008V7Z"></path>
  </svg> questions.web.js </summary> 

```javascript
import { Permissions, webMethod } from "@wix/web-methods";
import { items } from '@wix/data';

export const getRandomQuestions = webMethod(
    Permissions.Anyone,
    async (numOfQuestions) => {
        const allQuestions = await getAllQuestions();
        const numberOfItems = allQuestions.length;
        let randomQuestions = [];
        while (randomQuestions.length < numOfQuestions) {
            const randomNumber = Math.floor(Math.random() * (numberOfItems));
            let question = allQuestions[randomNumber];
            if (randomQuestions.indexOf(question) < 0) {
                randomQuestions.push(question);
            }
        }
        return randomQuestions;
    }
);


const getAllQuestions = webMethod(
    Permissions.Anyone,
    async () => {
        try {
            const request = await items.query('questions').find();
            if (request.items.length > 0) {
                return request.items;
            } else {
                throw 'no items found';
            }
        } catch (error) {
            console.error('an error was found in getAllQuestions function', error);
        }
    }
);
```
</details>

<details open> 
<summary> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 18" width="22" height="22">
    <path d="M16.003 15.18c0 .57-.11 1.01-.31 1.32.2.31.31.75.31 1.32 0 .94.33 1.22.53 1.24.27.02.481.25.471.52-.01.27-.22.48-.49.48-.521 0-1.512-.47-1.512-2.24 0-.51-.1-.74-.16-.81h-.06c-.06 0-.11 0-.16-.01a.505.505 0 0 1-.561-.29.522.522 0 0 1-.04-.21c0-.08 0-.17.04-.25.1-.22.35-.32.58-.27h.2c.06-.06.17-.29.17-.81 0-1.77.992-2.24 1.513-2.24.28 0 .5.22.5.5s-.22.5-.5.5c-.18.02-.511.3-.511 1.24l-.01.01Zm5.967 1.1c-.09-.22-.33-.33-.57-.28h-.211c-.06-.06-.17-.29-.17-.81 0-1.77-.991-2.24-1.512-2.24-.27 0-.48.21-.49.48-.01.27.2.5.47.52.2.02.53.3.53 1.24 0 .57.11 1.01.311 1.32-.2.31-.31.75-.31 1.32 0 .94-.33 1.22-.511 1.24-.28 0-.5.22-.5.5s.22.5.5.5c.52 0 1.512-.47 1.512-2.24 0-.51.1-.74.16-.81h.06c.06 0 .11 0 .15-.01.23.06.47-.05.57-.27.041-.08.041-.17.041-.25 0-.07 0-.14-.04-.21h.01ZM17.014 4H6.001C5.451 4 5 4.45 5 5v14c0 .55.45 1 1.001 1h7.008v-1H6.001V5h11.013v6h1.001V5c0-.55-.45-1-1-1Zm-9.01 7h7.008v-1H8.004v1Zm7.008-4H8.004v1h7.008V7Z"></path>
  </svg> Home </summary> 

```javascript
import { getRandomQuestions } from "backend/questions.web.js";

const numOfQuizQuestions = 5;
const questionValue = 100 / numOfQuizQuestions;
const greenBgColor = "#D2FFEB";
const redBgColor = "#FFE2E2";
const greyBgColor = "#EFEFEF";
const quizItems = [];

$w.onReady(function () {
    $w("#quizSection, #submitSection, #scoreSection").collapse();

    $w("#startQuizBtn").onClick(async () => {
        $w("#questionBox").style.backgroundColor = greyBgColor;
        $w("#startQuizBtn").label = "Loading quiz";
        $w("#startQuizBtn").disable();
        await initQuestionsData();
        $w("#welcomeSection, #invalidMessageText").collapse();
        $w("#quizSection, #submitSection").expand();
    });

    $w("#submitBtn").onClick(async () => {
        $w("#invalidMessageText").collapse();
        let isUserAnswersValid = await checkValidity();
        if (isUserAnswersValid) {
            await submitAnswers();
            $w("#scoreSection").expand();
            $w("#submitSection").collapse();
            $w("#scoreSection").scrollTo();
        } else {
            $w("#invalidMessageText").expand();
            $w("#invalidMessageText").text =
                "An error occured. Please check that you have answered all the questions.";
        }
    });

    $w("#tryAgainBtn").onClick(() => {
        $w("#scoreSection, #quizSection, #submitSection").collapse();
        $w("#welcomeSection").expand();
        $w("#startQuizBtn").enable();
        $w("#startQuizBtn").label = "Start Now";
    });
});

async function initQuestionsData() {
    const questions = await getRandomQuestions(numOfQuizQuestions);

    $w("#quizRepeater").data = questions;
    $w("#quizRepeater").forEachItem(($item) => { quizItems.push($item("#questionBox")) }) //store items for scrollTo onClick
    $w("#quizRepeater").onItemReady(($item, itemData, index) => {
        $item("#questionText").text = itemData.title;
        $item("#correctAnswerText").hide();
        index !== numOfQuizQuestions - 1 ? $item("#nextButton").onClick(() => scrollToNextItem(index)) : $item("#nextButton").delete();
        if (itemData.type === "radioGroup") {
            $item("#radioGroup").selectedIndex = null;
            $item("#radioGroup").resetValidityIndication();
            setRadioGroupOptions($item, itemData);
            $item("#radioGroup").expand();
            $item("#input").collapse();
        } else {
            $item("#input").value = null;
            $item("#input").resetValidityIndication();
            $item("#input").expand();
            $item("#radioGroup").collapse();
        }
    });
}

function scrollToNextItem(currentIndex) {
    if (quizItems[currentIndex + 1]) {
        quizItems[currentIndex + 1].scrollTo();
    } else {
        return
    }
}

function setRadioGroupOptions($item, itemData) {
    let opts = itemData.answersList.map((answer) => {
        return { label: answer, value: answer };
    });
    $item("#radioGroup").options = opts;
}

async function checkValidity() {
    let allInputsValidity = [];
    $w("#quizRepeater").forEachItem(($item, itemData, index) => {
        if (itemData.type === "input") {
            allInputsValidity.push($item("#input").valid);
            $item("#input").updateValidityIndication();
        } else {
            allInputsValidity.push($item("#radioGroup").valid);
            $item("#radioGroup").updateValidityIndication();
        }
    });
    for (let i = 0; i < allInputsValidity.length; i++) {
        const valid = allInputsValidity[i];
        if (!valid) {
            return false;
        }
    }
    return true;
}

async function submitAnswers() {
    let score = 0;
    $w("#quizRepeater").forEachItem(async ($item, itemData, index) => {
        let userAnswer;
        if (itemData.type === "input") {
            userAnswer = $item("#input").value;
        } else {
            userAnswer = $item("#radioGroup").value;
        }
        if (userAnswer.toLowerCase() === itemData.correctAnswer.toLowerCase()) {
            score = Math.ceil(score + questionValue);
            $item("#correctAnswerText").show();
            $item(
                "#correctAnswerText"
            ).text = `Great job, you got it right! The answer is ${itemData.correctAnswer}`;
            $item("#questionBox").style.backgroundColor = greenBgColor;
        } else {
            $item("#correctAnswerText").show();
            $item("#questionBox").style.backgroundColor = redBgColor;
            $item(
                "#correctAnswerText"
            ).text = `Sorry, thats incorrect. The correct answer is ${itemData.correctAnswer}`;
        }
        $w("#txtFinalScore").text = `Your total score is ${String(score)}`;
    });
}
```
</details>

<!-- Static content -->
## Get Help
--- 
### Join the community 

Join the [Wix Studio][discord-community] community on Discord, where experienced developers and fellow creators come together to share tips, troubleshoot issues, and collaborate.

### Hire a developer 

Building a coded solution on your own can be challenging. Let an experienced Wix developer build it for you, so you can keep working on your site or business.
Visit the [Wix Marketplace][wix-marketplace] to find a trusted developer. 

<!-- Predefined links -->
[discord-community]: https://discord.com/invite/GhdmDN926z 
[wix-marketplace]: https://www.wix.com/marketplace/brief-auto-match/web-developer?entry=velo&origin=examples-page "Wix Marketplace"