Alert message verification for empty checkboxes with "null" in JavaScript

I have integrated the native-validations library into my form validation process. Everything is working well, except for an error message that appears when I try to submit a group of checkboxes without selecting any. The error message displayed is "null".

You can see a demo of this issue by visiting this link and clicking on "submit" without filling in any fields: Demo Link

You can also check out the code sandbox here: Code Sandbox

It seems like there might be an error in the following function:

function checkBoxGroupValidate(event) {
       //get all checked checkboxes for a group and if its null then mark it invalid or valid
       var totalChecked = event.target.parentNode.querySelector("input[name$='[]']:checked");
       if (totalChecked === null) {
           var errorMessage = '';
           if(event.target.dataset.requireError){
               errorMessage = event.target.dataset.requireError;
           }else if(event.target.parentNode.dataset.requireError){
               errorMessage = event.target.parentNode.dataset.requireError;
           }else {
               errorMessage = OptionGroupMessage;
           }
           event.target.parentNode.classList.remove(SuccessClass);
           event.target.parentNode.classList.add(ErrorClass);
           if (event.target.parentNode.querySelector(HelpBlockSelector) === null) {
               event.target.parentNode.insertAdjacentHTML("afterbegin", MessageTag.replace("{0}", errorMessage));
           }
       } else {
           event.target.parentNode.classList.remove(ErrorClass);
           event.target.parentNode.classList.add(SuccessClass);
           var spanError = event.target.parentNode.querySelector(HelpBlockSelector);
           if (spanError !== null) {
               event.target.parentNode.removeChild(spanError)
           }
       }
   }

Answer №1

The issue with the querySelector returning null is because it is looking for the error message in child elements such as checkboxes which do not initially have the data-require-error attribute.

var errorMessage = groupParent.querySelector("input[name$='[]']").getAttribute('data-require-error');

Instead, it is recommended to directly access the parent element.

var errorMessage = groupParent.getAttribute("data-require-error");

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

Issue with title position when hamburger menu opens

My title, "Roberto Salas," is not staying in place when I resize the window or view it on my cellphone. You can see an example of this issue here. If the hamburger menu button drops down, the title is also not in the correct position. See an example here. ...

Can you show me how to divide a number by a comma after every two digits and then save the result into two separate

Given a variable var Number = 2425;, the task is to split it into two parts and store them in separate variables. var data = 24; var month = 25; What would be the most efficient way to achieve this using JavaScript? ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

How can you verify the value of a disabled HTML input element in TestCafe using Typescript?

TestCafe Typescript - how to verify the value of a disabled HTML input element? Despite being disabled for user interaction, I want to ensure that this element still holds the anticipated value. example public async checksomething(text: string) { co ...

Unfortunately, the input type number does not allow for the removal of decimal points

I need assistance with modifying the HTML code below. I want to remove the decimal point from the input field. Could anyone please provide instructions on how to accomplish this? <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ...

Display a hidden div on hover using JQUERY

How can I make a hover popup appear when submitting a form, and have it disappear only when the mouse is out of both the popup div and the submit button? Currently, the hover popup shows up but disappears when entering the popup. Can someone assist me in r ...

Modifying pagination numbers with Reactjs: A step-by-step guide

I am currently working on Reactjs (nextjs) and I have successfully integrated the "Nextjs" framework. The pagination is working fine, but the buttons are displaying as "1,2,3,20" instead of "1,2...20" (showing all numbers without using "..."). How can I mo ...

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...

Search results in Google Maps may sometimes be missing when adjusting the radius

I've been working on integrating the Google Maps Place Search API to find nearby mosques. Everything is functioning smoothly, but I've encountered a problem when I increase the radius parameter. Some results are missing compared to the previous s ...

Help me locate the error in this AngularJS mini evaluation, please

Check out the code here! Hello, you can find the code on the provided link. This is the HTML snippet: <div ng-app="testApp" ng-controller="myController"> <select name="current" id="current" ng-model="currentliga"> <option ng-rep ...

How come my uvmapped texture is flipping vertically when using iewebgl + threejs?

Currently in the process of developing a 3D viewer for game pads with the aim of customizing the pad using various colors and materials. Initially, I created a simple ".bin .js" loader with sample materials using Threejs r62 to create a visualizer prototy ...

Using Stringify to modify the value of a particular array in Local Storage

Uncertain of the accuracy of my question, but I am attempting to modify a value within a localstorage array. This is what my localstorage currently contains: [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","i ...

Tips for Converting a JavaScript Array into JSON

I am dealing with data structured like this: "team": "Yankees" "players": ["jeter", "babe ruth", "lou gehrig", "yogi berra"] In my code, I extract these values from a form where they ar ...

"An error has occurred: `nuxt.js - $(...).slider function not found`

I have integrated jQuery into my nuxt.js project by adding it to the nuxt.config.js file as shown below: build: { plugins: [ new webpack.ProvidePlugin({ '$': 'jquery', '_': 'lodash&apo ...

Within Codesandbox using Vue, the error message 'The property or method "children" is not defined in the instance, but is referenced during rendering.' appeared

Currently, I am in the process of creating a versatile State Manager that can seamlessly integrate with various Frontend Frameworks, including Vue. In order to showcase how the State Manager can be utilized within Vue, I have set up a simple codesandbox de ...

When using form_tag with :remote set to true, the div is not updated and instead navigates to a different page

Seeking to enhance a div upon form submission, I am utilizing Rails 3.1.1 and attempting to adjust existing coding found in another developer's tutorial. Here is an excerpt from my view file, specifically main.html.erb: <%= javascript_include_tag ...

What is causing me to be unable to concentrate on specific elements when utilizing react refs?

I encountered a strange scenario where I had a collection of references to various form elements like buttons, different types of inputs, and more. I then generated an error summary that, when clicked, automatically focused on the element in question, scro ...

Tips for dynamically assigning values to scope variables in AngularJS

My ng-model looks like this: <tr ng-repeat="user in users"> <input type="text" ng-model="code[user.id]"/> When I set $scope.code = {0: 'value'};, it works fine. However, if I try to pass a dynamic value like: var index = 0; $scope ...

Navigating Users After Form Validation in React - A Step-By-Step Guide

As a newcomer to React, I am currently working on a SignUp SignIn project. My goal is to route the user to the Login/SignIn page upon successful form validation. Below is my SignUp code: import React, { Component } from 'react'; import { Link } f ...

Updating HighCharts with fresh data through Ajax

I'm currently in the process of replacing the highcharts that I initially loaded through ajax. The idea is to obtain new values from the user, pass them via Ajax, and then display an entirely new graph (with a different type and data). Here's wha ...