Verifying if a checkbox is ticked prior to initiating a search

I'm encountering some issues with my checkbox functionality. I'm attempting to use event listeners on checkboxes to capture true or false values and then passing this data through another event listener on a button to verify that at least one checkbox is selected. I believe there must be a simpler way to achieve this task, preferably using pure JavaScript. Any guidance would be greatly appreciated. Below is the code snippet for reference.

<body>
    <script src="racquetObjects.js"></script>
    <div class="mainContainer">
      <div class="selectors">
        <form action="">
          <div class="checkboxes">
            <input type="checkbox" id="babolat" value="Babolat" />
            <label for="babolat">Babolat</label>
            <input type="checkbox" id="wilson" value="Wilson" />
            <label for="wilson">Wilson</label>
            <input type="checkbox" id="power" value="Power" />
            <label for="power">Power</label>
            <input type="checkbox" id="control" value="Control" />
            <label for="control">Control</label>
            <input type="checkbox" id="popular" value="Popular" />
            <label for="popular">Popular</label>
          </div>
          <button type="button" id="find">Find</button>
        </form>
      </div>
      <div class="racquetContainer"></div>
      <div class="bench"></div>
    </div>
    <script src="racquetFinderCB.js"></script>
    <script src="racquetFinder.js"></script>
  </body>

const findButton = document.querySelector("#find");
const checkboxes = document.querySelectorAll(
  ".checkboxes input[type=checkbox]"
);

const checkIfChecked = function(element) {
  element.checked ? return true : return false;
}

const verifySelection = () => {
  let isChecked = [];
  checkboxes.forEach((el) => {
    el.addEventListener("click", (e) => {
      isChecked.push(checkIfChecked(e.target));
    });
  });

  if (isChecked.includes(true)) {
    console.log("Ready to search!");
  } else {
    console.log("Please select an option");
  }
};

findButton.addEventListener("click", verifySelection);

Answer №1

This particular scenario showcases the utilization of an event listener for the form submission. It involves filtering an array of input elements, ensuring that only the checked items are captured in the checked variable.

The initial e.preventDefault() call serves as a test mechanism. You can remove this line if the form should be submitted (indicating at least one item was checked).

document.forms.find.addEventListener('submit', e => {
  let inputs = e.target.querySelectorAll('input');
  e.preventDefault(); // testing purposes
  let checked = [...inputs].filter(input => input.checked);
  if (checked.length > 0) {
    console.log('at least one item was checked');
  } else {
    e.preventDefault(); // stop form action
    console.log('no items were checked');
  }
});
<div class="mainContainer">
  <div class="selectors">
    <form name="find" action="">
      <div class="checkboxes">
        <input type="checkbox" id="babolat" value="Babolat" />
        <label for="babolat">Babolat</label>
        <input type="checkbox" id="wilson" value="Wilson" />
        <label for="wilson">Wilson</label>
        <input type="checkbox" id="power" value="Power" />
        <label for="power">Power</label>
        <input type="checkbox" id="control" value="Control" />
        <label for="control">Control</label>
        <input type="checkbox" id="popular" value="Popular" />
        <label for="popular">Popular</label>
      </div>
      <button id="find">Find</button>
    </form>
  </div>
  <div class="racquetContainer"></div>
  <div class="bench"></div>
</div>

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

Are you encountering issues with retrieving $http results from the cache?

During my initial $http requests, I am saving the results in cache using two functions in my controller. Both functions call the same function in a service which handles the $http request. The first function successfully saves the results in cache, but whe ...

Interested in learning how to code games using JavaScript?

Hi everyone, I'm currently exploring the world of Javascript and have been tasked with completing a game for a class project. The game involves a truck that must catch falling kiwis while only being able to move left or right. A timer is set for two m ...

How can I show the initial three digits and last three digits when using ngFor loop in Angular?

Greetings! I have a list of numbers as shown below: array = [1,2,3,4,5,6,7,8,9,10] By using *ngFor, I am displaying the numbers like this: <div *ngFor =" let data of array"> <p>{{data}}</p> </div> Now, instead of d ...

Iterating recursively through a tree structure to update properties using Mongoose

I have a unique structure resembling a tree that I've set up to store comments. Each "comment" acts as a node with a "parent" property linking it to another "comment" node. Additionally, I've included a "replyCount" field on each node to keep tra ...

Adding a three-dimensional perspective to an HTML5 canvas without utilizing CSS3 or WebGL

Here is a canvas I am working with: http://jsbin.com/soserubafe Here is the JavaScript code associated with it: var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var w = canvas.width; var h = canvas.height; var cw=canvas. ...

I could really use some assistance with this project for my friend

Whenever I click on the image, it only displays two out of the three possible alerts. How can I make it show all three? Here's my code: <!DOCTYPE html> <html> <head> </head> <body> <img src="http://www.build ...

Do I need to include success as a parameter in my Ajax call even if my function does not return any values?

When an image is clicked, I trigger an ajax call. The image includes an href tag that opens a different page in a new tab upon click. The purpose of this ajax call is to record the user's clicks on the image for telemetry purposes in a database table. ...

Create a responsive canvas with custom shapes

After designing a canvas with a gradient-filled circle, I encountered a challenge in making the canvas and the circle responsive to varying screen sizes. Initially, I attempted to use `vh` and `vw` units for the width and height of the canvas. However, ad ...

Searching for a document using the $eq operator in MongoDB within the context of Next.js - what is

In my Next.js code, I am fetching a document from MongoDB using a unique slug. Here is the code snippet: export async function getStaticProps(context) { const postSlug = context.params.postPage; const { db } = await connectToDatabase(); const posts ...

How can I create a parent div with cursor-pointer and apply inline styling to make all child elements

Is there a way to apply the cursor-pointer style to an entire div with inline CSS without it affecting just the white space around the child elements? I have tried using position and z-index without success. I am unable to use an external stylesheet for t ...

Is it possible to stack one Canvas on top of another?

Right now, I am engaged in a process that involves: creating a canvas and attaching it to a division applying a background image through CSS to that canvas. drawing a hex grid on the canvas placing PNGs on the canvas. animating those PNGs to show "movem ...

Facebook's Thumbs Down to My Code

I've been struggling to integrate a Facebook Like button on my blog using the following code: $("#fblike").append(" <iframe src='http://www.facebook.com/plugins/like.php?app_id=217624258276389&amp;" + window.location.href + "&amp;send ...

Tips for updating input values in real-time?

I am working with dynamic inputs that allow me to add and delete rows with inputs. These inputs include Material-UI timepickers, which have an input field with a clock icon. When I click on the icon, a clock appears. However, the values in this input field ...

JavaScript Toggle Visibility on Click

Click to reveal a new div <div id="box1">abc</div> <div id="box2" style="display:none;">awklnnbc</div> <div id="box3" style="display:none;">wgweilwe</div> <div id="box4" style="display:non ...

Combining Array Attributes to Create a New Property as a 'JSON String'

I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute. For example: [{ { "orderNo":"1", "description":"Item 1", "note": "Note 1" }, { "orderNo":"2", "description":"Item 2", ...

For handling the onSubmit event, utilize both axios and axios-mock-adapter

I am attempting to utilize both axios and axios-mock-adapter in a single location to consolidate multiple mocks, then export the axios instance for use elsewhere: axios.js import axios from 'axios'; let api = axios.create({ baseURL: 'h ...

Enhancing User Experience with Animated jQuery Progress Bar

I came across a cool tutorial on animating progress bars: The only issue was that the progress bar didn't utilize jquery, and there wasn't information on linking multiple buttons to it. After some searching, I found another tutorial that address ...

Exploring the use of functions in the setup method of Vue 3

I'm currently working on a simple app and utilizing mock-json-server to mimic http requests. Within my project, I have defined a function designed to retrieve the necessary information: import { ref } from 'vue' const getScores = () => ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

What issue could be causing trouble with my JavaScript animation?

Currently, I am working on designing a web-page and I have a specific vision in mind - I want an image of the moon to slowly rise up from the bottom of the screen to the top. Here's the HTML code that I have so far: <body> <div id="Moon" ...