Difficulty enforcing mandatory checkboxes

Seeking assistance on making checkboxes required.

I am creating a form using bootstrap 4 and validating it using the JS example from bootstrap documentation. I have added "novalidate" to the form, "required" to inputs, and included the following script:

  (function() {
  'use strict';
   window.addEventListener('load', function() {
    var form = document.getElementById('forms');
     form.addEventListener('submit', function(event) {
      if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
       }
      form.classList.add('was-validated');

      }, false);
      }, false);
  })();

Everything is working smoothly so far, but I now have multiple checkboxes and I want to validate them only if at least one is checked. Should I create a separate function for this or modify the existing one? Any help on this would be greatly appreciated.

Below is the code for the checkboxes:

    <div class="form-row">
<div class="form-group col-md-4">
  <label for="checkboxes">Indícios:</label>
  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" id="" type="checkbox" value="1">
    1
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="2">
    2
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="3">
    3
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="4">
    4
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="5">
    5
  </label>
</div>
</div>

<div class="form-group col-md-4">

<label for="checkboxes1">&nbsp</label>
  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="checkboxes1" value="6">
    6
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="7">
    7.
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="8">
    8
  </label>
</div>

  <div class="form-check">
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" value="9">
    9
  </label>
</div>

</div>
</div>

Thank you in advance for your help!

Answer №1

Are you familiar with jQuery? If so, you may find this helpful. Here's a function that you can integrate into your checkValidity method:

var validateCheckboxes = function() {
    return ($('.form-check-input:checked').length > 0);
};

This function specifically checks for any input elements with the class .form-check-input that are currently in the checked state within the HTML. If found, the checkbox validation will be considered valid.

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 utilize JavaScript for rotating and cropping a collection of images before uploading them to the gallery?

Struggling to implement file reader and croppie for local image editing (zoom / rotate / crop) before uploading. Seemingly stuck due to a potential DOM issue with the modal, unable to troubleshoot! FileReader () issues // // //create elements for image, ...

Creating image filters using an object in jQuery

I am faced with a challenge where I have multiple image tags nested within a div that has the class google-image-layout. Each image is equipped with various data attributes, including: data-anger="0" data-disgust="0" data-facedetected="0" data-fear="0" da ...

What is the best way to loop through strings in a request object?

I am currently working with Express and need to scan the POST requests to create an array called openingTimes. After that, I want to generate a MongoDB document based on the user inputs. The code snippet below is functional, but I am looking for a way to ...

The functionality of the Protractor right click feature is smooth, however, there seems to be an issue with selecting

https://i.sstatic.net/KoGto.png Even though I can locate the button within the context menu, I am facing difficulty in clicking it. The code mentioned below is successfully able to click the button, but an error message pops up indicating: Failed: script ...

Tips for retrieving the count from HTML using JavaScript:

I need to determine the count of list items in an unordered list within dir-pagination-controls. How can I achieve this using JavaScript? <dir-pagination-controls min-size="1" direction-links="true" boundary-links="true" class="pull-right ng-isolate- ...

``There seems to be an issue with the functionality of Passport.js' multiple login system

I'm encountering a strange issue with my login system. Everything seems to be working fine, including local login, Google login, and Facebook login. However, the problem arises when I attempt to register with Google after already registering with Face ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

The lightbox feature on the page is not functioning properly

On my website, I have a beautiful lightbox created using fancybox.net. You can check it out here: https://i.sstatic.net/R0OUM.jpg I also use gallery codes to display images in a gallery format. Below is the jQuery code I am using: $(document).ready(fun ...

Explore the functions of jQuery's .css() method and the implementation of

Could use some assistance with the .css() method in jQuery. Currently working on a mouseover css menu, and encountering an issue when trying to include this code: $(this).siblings().css({backgroundColor:"#eee"}); at the end of my script. It seems to int ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

Is it possible to resize the background-image style?

When using the regular img tag in HTML, you can specify the width and height, and the browser will scale the image. If the dimensions are not too different from the original, the result is usually decent. For example, you can scale the avatar image to 32x ...

Using Laravel to retrieve the selected value of a dynamically generated radio button through a for loop in jQuery

In my view, there is a form with dynamically populated radio buttons sourced from the database. The code snippet for this functionality is as follows: <div class="row"> @foreach($status as $s) <div class="col-md-6"> <label class ...

Reinitialize the bootstrap modal every time it is closed to ensure a fresh start and maintain consistent functionality

$(".modal").on("hide.bs.modal", function(){ $(".modal-bodydata").html(""); }); In my application, there is a feature where users can upload images related to a book. Once the images are uploaded successfully, the modal closes and the contents displa ...

Is there a superior jQuery scrolling plugin available compared to scrollTo?

ScrollTo may not offer the smoothest animation as compared to others on the market, and it seems like it hasn't received any recent updates... Are there any newer plugins that exceed scrollTo's performance, or is it still considered the best in ...

Executing a JavaScript function within MainPage.xaml.cs codebehind file in a Windows application

I am currently working on a project developing a Windows 8.1 app using HTML5 and Javascript (Silverlight). I have encountered an issue with implementing the functionality for the hardware back button. Within the MainPage.xaml.cs Codebehind file, I need to ...

What is the method to retrieve response text?

This is the content of my register.js file: var formdata = new FormData(); formdata.append("name", name.value); formdata.append("username", username.value); formdata.append("email", email.value); formdata.append("password", password.value) ...

Mapping Store Fields to JSON Properties in ExtJS: A Complete Guide

I am working with a JSON data object that includes exchange rates information: { "disclaimer": "Exchange rates provided for informational purposes only and do not constitute financial advice of any kind. Although every attempt is made to ensure quality, ...

"Uncovering the mystery of the missing element in Jquery's open

I have developed a click-to-show feature that opens and closes a div from left to right. You can view the demo here on jsfiddle.net In the demo, you will find a green-colored div. Upon clicking this div, another div opens from left to right. An interesti ...

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

Extract PHP variable and incorporate it into JavaScript code

After doing some research online, I was unable to find a solution to my issue. Can anyone provide assistance with this problem? I currently have a javascript variable that contains the name of a PHP session address. I am trying to access this session valu ...