Verify if the element has been clicked and chosen before proceeding to the next action

It has come to my attention that users are able to submit answers without actually making any selections from a menu of buttons. This results in an empty array being printed to the console, which is not the intended behavior.

I am seeking a solution that will prevent users from submitting answers without first selecting options from the menu. The array should always contain either A, B, C, or D, or a combination of these letters. If a user attempts to submit without making any selections, they should receive an error message.

I am facing difficulties implementing this functionality, as the buttons are generated dynamically using a map function based on a list. Any advice on how to achieve this would be greatly appreciated. Thank you!

<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <style media="screen">
    .buttons {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }

    #buttonGallery {
      margin: 10px;
      padding: 10px;
      border: solid 2px black;
      width: 155px;
    }

    #done {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }
  </style>
</head>

<body>
  <div id="buttonGallery">
    <div id="done">
      <p>done</p>
    </div>
  </div>
  <script type="text/javascript">
    let $buttonGallery = $("#buttonGallery");
    let myList = ["A", "B", "C", "D"];
    let myColors = ["red", "green", "blue", "red"];
    let clicked = [];

    myList.map(function(letter, index) {
      let $button = $("<div></div>")
        .addClass("buttons")
        .attr("id", "button_" + letter)
        .html("<p>" + letter + "</p>")
        .on("mouseenter", function() {
          $(this).css("background", myColors[index]);
        })
        .on("mouseleave", function() {
          if (!$(this).hasClass('selected')) {
            $(this).css("background", "transparent");
          }
        })
        .on("click", function() {
          $(this).css("background", myColors[index]);
          $(this).toggleClass('selected');
          clicked = [];

          // push clicked variables to array
          let syms = document.querySelectorAll('.selected');

          for (let n = 0; n < syms.length; n++) {
            if (!clicked.includes(syms[n].textContent)) {
              clicked.push(syms[n].textContent);
            }
          };

          // send data to server
          // console.log('clicked array', clicked);
        })
      $("#done").before($button);
    });

    $("#done").on("click", clearColor);

    function clearColor() {
      console.log('clicked array', clicked);

      $(".buttons").css({
        backgroundColor: 'transparent'
      });
      $(".buttons").removeClass('selected');

      // reset clicked list after recording button selections
      clicked = [];
    }
  </script>
</body>
</script>

</html>

Answer №1

To check if the user has selected all the values, you can simply utilize the .length function along with the .html() method to display any errors.

Execute the code snippet below to observe the error message if you have not selected A, B, C, or D

let $buttonGallery = $("#buttonGallery");
let myList = ["A", "B", "C", "D"];
let myColors = ["red", "green", "blue", "red"];
let clicked = [];

myList.map(function(letter, index) {
  let $button = $("<div></div>")
    .addClass("buttons")
    .attr("id", "button_" + letter)
    .html("<p>" + letter + "</p>")
    .on("mouseenter", function() {
      $(this).css("background", myColors[index]);
    })
    .on("mouseleave", function() {
      if (!$(this).hasClass('selected')) {
        $(this).css("background", "transparent");
      }
    })
    .on("click", function() {
      $(this).css("background", myColors[index]);
      $(this).toggleClass('selected');
      clicked = [];

      // push clicked variables to array
      let syms = document.querySelectorAll('.selected');

      for (let n = 0; n < syms.length; n++) {
        if (!clicked.includes(syms[n].textContent)) {
          clicked.push(syms[n].textContent);
        }
      };

      // send data to server
      // console.log('clicked array', clicked);
    })
  $("#done").before($button);
});

$("#done").on("click", clearColor);

function clearColor() {
  if (clicked.length == 4) {
    console.log('Yay! All selected');
    $('.error').html('')
  } else {
    $('.error').html('Please select A, B, C, D before clicking done')
  }

  $(".buttons").css({
    backgroundColor: 'transparent'
  });
  $(".buttons").removeClass('selected');

  // reset clicked list after recording button selections
  clicked = [];
}
.buttons {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }

    #buttonGallery {
      margin: 10px;
      padding: 10px;
      border: solid 2px black;
      width: 155px;
    }

    #done {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <style media="screen">

  </style>
</head>

<body>
  <div id="buttonGallery">
    <div id="done">
      <p>done</p>
    </div>
    <div class="error">

    </div>
  </div>
</body>

Answer №2

Verify if the length of the clicked item is greater than zero


function updateColor() {
      if(clicked.length ===0){ 
        alert();
        return false;
        }
      console.log('clicked array', clicked);
...

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

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

What is the best way to establish a header in the login route that allows the browser to remember the user's login status?

I have successfully implemented a user login backend and everything seems to be working fine. However, when I try to access a user detail after logging in, I am faced with an authorization issue preventing me from exploring other routes. How can I store th ...

Click on a plane within a three.js environment to determine the X Y position within it

When using a raycaster, I can successfully obtain the current object (in this case, a plane) under the mouse. However, I am seeking a more precise X and Y value for the mouse position INSIDE the plane. var vector = new THREE.Vector3( ( event.clientX / win ...

Creating a nested array of objects using a recursive function

How can I utilize my getChildren() function to create a larger function that takes my two main arrays objs and objRefs, and generates a single array of objs showcasing their parent/child relationship? Below are the two primary data arrays: const objs = [ ...

Upon the initial gallery load, the images are appearing on top of each

Currently, I am working on creating a gallery page for my website using the Isotop filtering plugin. To view the live gallery, you can visit: carroofies.com/gallery The main issue I am encountering is with the initial load of the page, where the images ov ...

Selecting a specific element and attaching a particular class to this element, but directing it towards a different element that shares the same index in a separate node list

I am working on a project where I have two sets of identical images - one is displayed in a gallery format and the other set is hidden until its corresponding gallery image is clicked, creating a lightbox effect. For example: <ul id="gallery"> ...

Preventing clicks within an iframe

Within an iframe, I have HTML content that includes hyperlinks. I need to prevent clicks on these hyperlinks. I managed to accomplish this using jQuery as shown below. However, I prefer not to use jQuery for this task. How can I achieve the same result ...

Passing data from PHP to an AJAX error message

Can a PHP error trigger the return of a timestamp variable to an AJAX request? I am looking to implement a timestamp on the server side and send it back if a PHP error occurs. Best regards / H ...

PHP implementation of a webpage supporting multiple languages

I encountered an issue while creating a multi-lingual page successfully. I utilized CssFlipper to generate the RTL Bootstrap file and everything was functioning perfectly, except for the fact that when I switch the language to Arabic, the slider on the pag ...

Tips for Retrieving a JavaScript Variable's Value in JSP

In my JSP file, I have implemented dynamic rows of textboxes using JavaScript. Now that I have input values into these fields, how can I retrieve those values in my result JSP page? ...

Is it possible to access a file on the client's PC without transferring the file to the server?

Is there a way to read an excel file directly from a user's PC in a web app and insert the cell values into a MySQL database cell by cell? Or should the file be uploaded to the server first before being read? (The web app is built using JSP) ...

The navigation bar logo on my website has mysteriously vanished

Even though my main website is built with Wordpress, I decided to start a blog using Tumblr. You can visit my website here: And here is my blog: I tried to replicate the same structure of my website on my Tumblr theme. However, I encountered an issue w ...

The React modal window stubbornly refuses to close

import c from '../Profile.module.css'; import { useState } from 'react'; import { createPortal } from 'react-dom'; import Modal from '../Modal/Modal'; const TransactionItem = (props) => { const modalRoot = ...

Managing events with classes

I have multiple divs with the same class. When one of these divs is clicked, I want to change the display of the other divs to 'block'. Currently, I am using inline JavaScript for this functionality, but I would like to achieve it without inline ...

The legends on the Google chart are having trouble being displayed accurately

Take a look at the screenshot below to pinpoint the sample issue. While loading the graph UI with Google Charts, the legends data is showing up but not appearing correctly. This problem seems to occur more frequently on desktops than on laptops. Any advi ...

Sending a form field through ajax and subsequently submitting it through php

I am currently in the process of customizing a WordPress plugin that utilizes a front-end form powered by ajax/jquery to submit entries to various logs. My goal is to incorporate an extra field, pass its value to the .js file, and submit this additional in ...

if a user does not click on an element in jQuery

Looking for a clever jQuery trick to determine if something other than a specific element (and its descendants) was clicked? <body> <header></header> <p>stuff<p> <div class="floating-form"> <form>more st ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Rails Unobtrusive JavaScript (UJS) does not seem to be connecting the data-remote

Version of Rails: 3.2.1 Version of Ruby: 1.9.3p125 Browser Used: Chrome 18.0.1025.162 Developers Operating System: Mac OS/X Lion Server's Operating System: CentOS 5 I am attempting to utilize :remote in my link_to call in order to request HTML co ...