Insert a clickable element within an HTML document

I have an idea for a questionnaire that includes questions and an interactive element at the end. At the completion of the questionnaire, there will be a button labeled "display answers" which users can click to reveal the correct responses.

For example, if I were to use this specific question:

<p class="question">1. What is the answer to this question?</p>        

<ul class="answers">            
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>                   
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>            
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>            
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>       
</ul>

I am curious about how to incorporate a feature where pressing a button on the page would indicate whether the selected answer is correct or not.

Answer №1

<p class="question">1. Can you solve this riddle?</p>        

<ul id="answers" class="answers">            
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Solution A</label><br/>                   
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Solution B</label><br/>            
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Solution C</label><br/>            
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Solution D</label><br/>
<input type="button" value="submit" onClick="showAnswer()" />       
</ul>

<span id="info"></span>

Next, incorporate the following script above that section of code:

<script>
    function showAnswer(){
        if(document.getElementById('q1a').checked){
            document.getElementById('info').innerHTML = "Impressive!";
        }else{
            document.getElementById('info').innerHTML = "Incorrect!";
        }
    }
</script>

I'm unable to assist with your quiz, so in this case Solution A is deemed correct.

Answer №2

  • There are two .addEventListeners() that need to be set up:

    • One on the container where all questions and answers are held (e.g. #QA1)
    • The other on the button used to finish the quiz (e.g. #btn1)
  • When a user selects an answer, #QA1 listens for clicks on any radio button (e.g. .answers). It's more efficient to use one event listener for multiple elements than adding one to each individual radio button. By comparing the clicked element with the listening element, we can identify the id of the radio button. Refer to this article for more information.

  • Once the id of the clicked radio button is known (as described in the previous reference), it is added to an array (e.g. answers[]).

  • When the user finishes, they click the "DONE" button which triggers the click event of #btn1.

    • A for loop is used to compare elements in the answer[] and key[] arrays. During each iteration, matching elements are compared.
    • The results are displayed on #out1, an <output> element within an ordered list (<ol>).

Snippet

var qa = document.getElementById('QA1');
var btn1 = document.getElementById('btn1');
var answers = [];
var key = ['q1c', 'q2a', 'q3d'];

qa.addEventListener('click', function(event) {
  if (event.target != event.currentTarget) {
    var choice = event.target.id;
    answers.push(choice);
  }
  event.stopPropagation();
}, false);

btn1.addEventListener('click', function(event) {
  event.preventDefault();
  var qList = document.getElementsByClassName('question');
  var out1 = document.getElementById('out1');

  for (var i = 0; i < qList.length; i++) {
    if (answers[i] === key[i]) {
      out1.innerHTML += '<li>' + answers[i] + ' is correct</li>';
    } else {
      out1.innerHTML += '<li>' + answers[i] + ' is incorrect, the correct answer is ' + key[i] + '</li>';
    }
  }
}, false);
body {
  font: 400 16px/1.45'Verdana';
}
* {
  font: inherit;
}
.question {
  margin-bottom: 15px;
}
.answers {
  list-style: none;
}
.answers li {
  margin-left: -15px;
}
input[type="radio"] {
  position: relative;
  top: 2.25px;
}
#btn1 a {
  text-decoration: none;
}
#out1 {
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

<ol id="QA1" class="QA">
  <li id="q1" class="question">What is the answer to this question?

    <ol class="answers">

      <li>a.
        <input type="radio" name="q1" value="a" id="q1a" />
        <label for="q1a">Answer</label>
      </li>

      <li>b.
        <input type="radio" name="q1" value="b" id="q1b" />
        <label for="q1b">Answer</label>
      </li>

      <li>c.
        <input type="radio" name="q1" value="c" id="q1c" />
        <label for="q1c">Answer</label>
      </li>

      <li>d.
        <input type="radio" name="q1" value="d" id="q1d" />
        <label for="q1d">Answer</label>
      </li>

    </ol>
    <!--answers-->

  </li>
  <!--question-->
  <li id="q2" class="question">What is the answer to this question?

    <ol class="answers">

      <li>a.
        <input type="radio" name="q2" value="a" id="q2a" />
        <label for="q2a">Answer</label>
      </li>

      <li>b.
        <input type="radio" name="q2" value="b" id="q2b" />
        <label for="q2b">Answer</label>
      </li>

      <li>c.
        <input type="radio" name="q2" value="c" id="q2c" />
        <label for="q2c">Answer</label>
      </li>

      <li>d.
        <input type="radio" name="q2" value="d" id="q2d" />
        <label for="q2d">Answer</label>
      </li>

    </ol>
    <!--answers-->

  </li>
  <!--question-->
  <li id="q3" class="question">What is the answer to this question?

    <ol class="answers">

      <li>a.
        <input type="radio" name="q3" value="a" id="q3a" />
        <label for="q3a">Answer</label>
      </li>

      <li>b.
        <input type="radio" name="q3" value="b" id="q3b" />
        <label for="q3b">Answer</label>
      </li>

      <li>c.
        <input type="radio" name="q3" value="c" id="q3c" />
        <label for="q3c">Answer</label>
      </li>

      <li>d.
        <input type="radio" name="q3" value="d" id="q3d" />
        <label for="q3d">Answer</label>
      </li>

    </ol>
    <!--answers-->

  </li>
  <!--question-->

</ol>
<!--QA-->
<button id="btn1"><a href="">DONE</a>
</button>
<ol>
  <output id="out1"></output>
</ol>

Answer №3

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Questionnaire</title>

</head>
<body>
<p>1. What is the answer to this question?</p>     

  <ul onclick="man()">
<input type="radio" name="q1" value="a">Answer 1<br/>               <input type="radio" name="q1" value="b">Answer 2<br/>            
<input type="radio" name="q1" value="c">Answer 3<br/>            
<input type="radio" name="q1" value="d">Answer 4<br/>       
  </ul>
  <p id="m"></p>
<script>
  var man = function(){
    document.getElementById("m").innerHTML = 'The correct answer is: Answer 1';
  }
  </script>
</body>
</html>

In a straightforward manner, I have crafted the solution using CSS Document object model for those seeking simplicity. Additional insights can be found at HTML CSS DOM

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

Passing an event from a Vue3 parent component to its child component

How do I trigger a load event from a parent component to the child component? The child component needs to be able to listen for the load event in a slot-defined element and then perform some actions with the event. For example: <template> <slot ...

What is the best way to attach two separate event listeners to a single button?

I'm attempting to have one button trigger two different functions, but I haven't been successful so far. I tried adding the second event listener as indicated by the // part, but it didn't work. The two functions should be executed sequentia ...

Firefox Issue: SetTimeout Redirect Function Not Functioning Properly

Working on a page that redirects users to an installed application or a webpage as a fallback. This is implemented using ClientScript.RegisterStartupScript when the page loads, with a Javascript snippet like this: <script type='text/javascript&apo ...

Unable to utilize ES6 syntax for injecting a service

I am encountering some issues while trying to implement a service into a controller using ES6 syntax. CategoriesService.js export default class CategoriesService { constructor() { this.getCategories = function ($q) { var deferred ...

Triggering an error message when a user attempts to submit an incomplete angular form

Working on an Angular form where users advance to the next step by clicking a button, but it remains disabled until all fields are valid. I'm wondering how I can implement a custom class to highlight incomplete fields when the user tries to move to t ...

The jQuery script version 3.5.1 encountered an error at line 4055 where DataTables was unable to access the property "aDataSort" due to it

Hey there, I'm currently facing a small challenge while trying to incorporate Datatables within a bootstrap modal to display the results of a SQL Server query. The main requirement is to provide the option to export the data as an Excel file or in oth ...

The error I encountered with the Typescript React <Select> onChange handler type was quite

Having an issue while trying to attach an onChange event handler to a Select component from material-ui: <Select labelId="demo-simple-select-label" id="demo-simple-select" value={values.country} onChange={handleCountryChange} ...

Script that was generated dynamically is failing to run

I have a situation where I am adding a script tag, along with other HTML content, to my current document after making an AJAX call. However, the script is not executing as expected. //Function to handle response function(responseText){ document.getEle ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

The form submission button fails to function when the onsubmit function returns false

When submitting, I check two fields. If one of the two fields is checked, then I return true; otherwise, I return false. The issue I'm facing is that even when I check one of the checkboxes, the submit button does not seem to work (I use console.log() ...

What could be the reason for the three.js scene failing to render in my Svelte application?

Scene.svelte <!-- Start by binding a container, then add the renderer to this container onMount --> <script> import { onMount } from 'svelte'; import * as THREE from 'three'; let container; onMount(async () = ...

"Employing a Backend Task Runner for a jQuery-Based Mobile Application

Currently, I am utilizing jQuery Mobile in conjunction with HTML5 to provide support for Android and iOS devices. Is there a control or technology that functions similarly to a background worker? My goal is to send data to the server without interrupting t ...

Verify the presence of a particular attribute in an HTML tag using Capybara and polling techniques

In my HTML code, the attributes of buttons (such as "AAAAA") will change based on external events. This real-time update is achieved through AJAX pooling. <div class="parent"> <div class="group"><button title="AAAAA"/></div> <di ...

Leverage array mapping functionality to generate React components within a separate component

Currently, I am retrieving data from an API and storing the results in an array. The issue arises when trying to map the array to a child component since it is initially empty. How can I ensure that the array mapping only executes when there is data in the ...

Develop a time-sensitive store system using HTML and JavaScript that toggles between open and closed status based on set

I am looking to develop a time-based Open/Closed store using HTML and JavaScript. The concept is that on Fridays, the element with id="friday" should be displayed, otherwise, show the element with id="week". Additionally, if the time i ...

Incorporating JavaScript into a Node.js project's Jade template

I'm attempting to integrate JavaScript into a jade template page. The code I have written is: script(src='/public/javascripts/scr1.js') and the JavaScript file is located in that directory. Within the script, I have written alert("doesnt wor ...

What could be causing my chosen value to remain unchanged after being copied from a controller?

I am struggling with controlling a <select> element using both ng-model and ng-options: <select ng-model="user.option" ng-options="value.label for (key, value) in data.options"> <option value="">Select value</option> ...

Email Template Concern

I have been encountering an issue with my Windows Application as it sends email using Email template images. However, when sent to a different SMTP server, the result is not consistent - it attaches the template images as attachments. Currently, I am util ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...