Wix Code: Retrieving and comparing data from specific fields in my database collection

Hey, I’m trying to use wix code to create a multiple choice question quiz. I have a database called MCQ where every item is a question and there are fields containing both right and wrong answers as well as other information to be used or displayed.

I have a field called rightAnswer which stores values 1-4 based on which of the four answers is right for that question, and a field called userAnswer which takes in a user submitted value from 1-4 using radio buttons and the submit button on the actual web page. (Note: while they use numbers both fields are text values because that is the format for radio button values)

Having received an answer from the user, I want to be able to compare the two values and then pop-up a “right” or “wrong” message, but I’m struggling with being able to retrieve a specific field for a given data item.

I started with something like this:

import wixData from ‘wix-data’;
var userAns = null;
var rightAns = null;

export function submit_click(event) {

userAns = wixData.get("MCQ", "userAnswer"); 

rightAns = wixData.get(“MCQ”, “rightAnswer”);

console.log("user Answer after:",userAns, "right answer after:", rightAns); 

if (userAns === rightAns)
$w(‘#right’).show();
else
$w(‘#wrong’).show();

}

But I know this is incorrect because the get() function retrieves entire items. I’ve been trying to use the query() function but I’m not sure how to do that. How do I retrieve the userAnswer and rightAnswer data fields for a given specific item?

Hi Ishaan,

Can you share some insights in how user’s answer is saved to database: are you using code or have bound an input to a dataset?

1 Like

Hi,
I’ve bound their input to my dataset. The dynamic page contains four radio buttons each corresponding to an answer, when the user hits submit, which answer they selected is recorded to the database in a field called userAnswer. To simplify things the radio buttons have values 1, 2, 3, or 4 and each question in the database has a field called rightAnswer that contains information on which of the answers is right as a number 1-4.
Once a user input is recorded, I would like to use wix code on the page to retrieve their answer and compare it to the right answer to see if they were right or wrong.
I have attached some photos for clarity, it is a sexual health education quiz.

@ishaanpat
You can use Dataset’s method onAfterSave to register a callback which will be executed when user submits data. This callback will receive the item that was submitted to collection and you can perform your comparison there. More information and code samples about onAfterSave can be found here
Let me know if you need further assistance. Good luck!