Tips for verifying the accuracy of a user's input in a quiz

How can I validate a user's input in a quiz scenario?

Imagine a quiz where users have to guess the origin of a food item based on an image displayed. If the first picture is from Turkey, followed by Greece, India, and Mongolia, how can I verify if the user's input matches the correct answer?

I am implementing a text input field for this feature instead of using a JavaScript modal.

Below is the code snippet for the input box:

<input class="end" id="guess" onclick="guess()"placeholder="Make a Guess!" style="border-radius: 31px; width: 20%; height: 62px; line-height: 1.2; color: mediumslateblue; padding: 0 35px; font-size: 16px; border-style: 7px solid yellow; visibility: hidden;">

Answer №1

Your code snippet is missing essential details for us to analyze thoroughly. Based on my understanding, it seems like you should swap out "onclick" with the "oninput" event handler. The oninput event triggers every time a new character is entered into the input field.

One suggestion is to cross-check the input value against the expected answers provided.

const checkAnswer = () => {
    let userInput = document.querySelector("#guess");
    if(userInput.value.toLowerCase() === "turkey"){
        console.log("You got it right!");
    }
}
<input type="text" id="guess" oninput="checkAnswer()">

Answer №2

Simply link the image's file name to a user's entry. It is recommended to utilize multiple-choice input (drop down) to prevent typographical errors.

Answer №3

Set up a question and answer database to test user responses:

const data = {
  question: 0,
  db: [
    {
      answer: "turkey",
      img: "tr"
    },
    {
      answer: "greese",
      img: "gr"
    },
    {
      answer: "india",
      img: "in"
    },
    {
      answer: "mongolia",
      img: "mn"
    },
  ]
};
function checkAnswer()
{
  const text = document.getElementById("guess").value.trim().toLowerCase();
  document.getElementById("result").textContent = text == data.db[data.question].answer ? "correct" : "wrong";
  
}

function setQuestion()
{
  data.question = Math.floor(Math.random() * data.db.length); //choose random question
  document.getElementById("question").src = "https://cdn.ipregistry.co/flags/noto/" + data.db[data.question].img + ".png";
  document.getElementById("hint").textContent = data.db[data.question].answer;
}

setQuestion()
<img id="question" onclick="setQuestion()">

<input class="end" id="guess" placeholder="Take a Guess!" style="border-radius: 31px; width: 20%; height: 62px; line-height: 1.2; color: mediumslateblue; padding: 0 35px; font-size: 16px; border: 7px solid yellow;">
<button  onclick="checkAnswer()">Submit Answer</button>
<div>
Hint: <span id="hint"></span>
</div>
Result: <span id="result"></span>

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

Is it possible to consolidate all CSS code into a single Style?

Recently diving into the world of HTML, I find myself tackling CSS tasks to enhance the look of my website. It's been interesting experimenting with different styles for each CSS code snippet. Each paragraph with a unique ID is getting its own special ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

What steps can be taken to safeguard the integrity of document.referrer against alterations by third-party scripts

My website is currently using a third-party script called Chaordic loader.js for product recommendations, but I am facing an issue where it overrides the document.referrer with inaccurate information, causing me quite a headache. Query: Is there a way to ...

What are some improvements I can make to enhance my jQuery code?

I have created a JavaScript function to display and hide information on a team page in a subtle manner. On the page, there are 3 emblems representing different teams and each emblem has a corresponding set of descriptions. When hovering over an emblem, the ...

What is the best way to retrieve the parent of the initial jQuery object?

At the bottom of a lengthy table containing multiple button.enter-match elements, I am using the following code: $("button.enter-match") .button() .on('click', function() { $("form.enter-match").dialog({ modal: true, height: ...

Creating dynamic nested objects using Javascript

In my quest to create serialized objects within the main object, I have come up with the concept of a solar system as an example of nesting. This allows me to access a variable by referencing it like this: universe.system1.planet4.x The hierarchy is univ ...

Adjust the alignment of text within the <select> tag to the right in Safari browser

Is there a way to align text right in a select option tag? <select style="direction:rtl;text-align:right"> <option value="" selected="">همه</option> <option value="1">راهبر سيستم</option> <option v ...

Receiving text from a server that restricts cross-domain ajax requests

Is there a way to retrieve a txt file from another server and display it in a div using jquery ajax? $("#div1").load("www.serverA1d.com/demo_test.txt"); When attempting to do this, the following error is displayed: Origin is not allowed by Access-Con ...

What is the best approach for addressing this problem using Mobile HTML5?

I am currently in the process of developing a Cordova application utilizing jQuery Mobile. In my application, there is a functionality that displays an array of words to the user using a for loop. <div id=page1div></div> <script> $pa ...

Tips for preventing errors in JavaScript date formatting

Currently, I am utilizing the DHTMLX Scheduler within my web application and aiming to access data for each event. Fortunately, I discovered a method to achieve this using scheduler._events which provides the following information: 1581498064943: {…} ​ ...

Add a space following each individual character using CSS styling

Imagine we start with this HTML: <h2>TITLE</h2> Can CSS alone transform it into something like this: <h2>T I T L E</h2> The goal is to justify the letters within the title over a specified width without relying on server-side so ...

What sets $emit and $dispatch apart in Vue.js?

Vue 2.0 has deprecated the use of $dispatch and $broadcast. I have noticed that $dispatch is similar to $emit. What are the key differences between them? Can we safely replace $dispatch with $emit during migration? ...

Is it necessary for me to create a module for every individual file?

Just diving into Angular and trying to figure out the best way to modularize my app. app toolbar toolbar.module.js menu.html index.html search.html sub-system-1 subSystem1.module.js directive-templat ...

Selecting CSS Properties with jQuery

I am trying to make an image change color to blue and also change the background color to blue when it is clicked inside a div. However, my code doesn't seem to be working as expected. Is there a more efficient way to apply CSS to elements? FIDDLE v ...

The res.download method in a node.js express app does not display the correct filename upon downloading

Starting with what I have: core.app.get('/download/:key', function (req, res) { require("./../../module/fileupload.js").download(req.params.key, function(file, filename) { console.log(file + " - " + filename); if (file != nul ...

Creating a banner image that scrolls while maintaining a fixed size

I'm looking to add a banner image with a scrolling effect as users navigate down the page, but I'm not sure what this technique is called. An example of what I'm trying to achieve can be seen on this site. As the user scrolls down, the res ...

Adding the classname "active" in ReactJS can be achieved by utilizing the `className` attribute within

I am facing an issue with adding the active classname in my code. Can anyone suggest a solution to add the active classname for this section: <li onClick = {() => onChangeStatus({status: 'on-hold'})} className = {appState === {'status& ...

Personalizing CSS classes in ASP.NET

In the project I'm currently developing, users will have the ability to customize the font color of header titles. These header titles are styled using values from a cssClass, which includes properties such as font-size, font-color, font-weight, and ...

When initializing a new instance of Stripe using cartalyst/stripe-laravel, an error occurs stating "The Stripe API key has not been properly defined!"

I am eager to explore Stripe and learn how to process payments. Currently, I am utilizing the cartalyst/stripe-laravel package to create a new instance of Stripe following the instructions provided here. The code snippet should resemble this: $stripe = ...

What is the best way to display up to 8 items in a row using flexbox?

I'm looking to display my items in a grid system with equal spacing between each item per row. While using space-between works for the most part, I've encountered an issue with odd numbers of items. In this case, the last items in a row should be ...