Verify whether the input checkbox is blank with the help of JavaScript

I have created a dropdown filter with checkboxes for gender and category selection. Now, I want to ensure that the user selects at least one checkbox from each section (gender and category). However, I am struggling to figure out how to determine if a checkbox is empty or not.

Below is a snippet of the form for the filter dropdown:

<form class="" method="GET" action="manage_product.php">
    <h6 class="dropdown-header px-0">Gender</h6>
    <div class="form-check">
        <input class="form-check-input" name="genderFil[]" type="checkbox" value="M" class="genderFil" id="genMale" <?= ($isMale == 1) ? "checked" : ""; ?>>
        <label class="form-check-label" for="genMale">Male</label>
    </div>

...

<input type="submit" class="button_primary" name="applyFilter" value="Apply" onclick="checkFilter()">
</form>

Here is my attempted JavaScript code for checking the selected checkboxes:

function checkFilter()
{
    var res = true;

    var checkedGender = $('input[class="genderFil"]:checked').length;
    if(checkedGender < 1)
    {
        alert("Please select at least one gender!");
        res = false;
    }

    var checkedCategory = $('input[class="categoryFil"]:checked').length;
    if(checkedCategory < 1)
    {
        alert("Please select at least one category!");
        res = false;
    }
    
    return res;
}

The form can only be submitted if there is at least one gender and one category checkbox checked.

If anyone knows how to detect whether a checkbox is empty or not, please share your insights!

Answer №1

This solution is effective.

function validateFilters()
{
    var result = true;


    var checkedGender = document.getElementById('genderSelector').querySelectorAll('input[type="checkbox"]:checked').length;        
    if(checkedGender < 1)
    {
        alert("Please choose at least one gender!");
        result = false;
        return result;
    }


    var checkedCategory = document.getElementById('categorySelector').querySelectorAll('input[type="checkbox"]:checked').length;
    if(checkedCategory < 1)
    {
        alert("Please select at least one category!");
        result = false;
        return result;
    }

    return result;
}
<form class="" method="GET" action="manage_product.php" onsubmit="return validateFilters();">
    <div id="genderSelector">
        <h6 class="dropdown-header px-0">Gender</h6>
        <div class="form-check">
            <input class="form-check-input" name="genderFil[]" type="checkbox" value="M" class="genderFil" id="genMale" <?= ($isMale == 1) ? "checked" : ""; ?>>
            <label class="form-check-label" for="genMale">Male</label>
        </div>
        <div class="form-check">
            <input class="form-check-input" name="genderFil[]" type="checkbox" value="F" class="genderFil" id="genFemale" <?= ($isFemale == 1) ? "checked" : ""; ?>>
            <label class="form-check-label" for="genFemale">Female</label>
        </div>
    </div>

    <div class="dropdown-divider"></div>

    <div id="categorySelector">
        <h6 class="dropdown-header px-0">Category</h6>
        <div class="form-check">
            <input class="form-check-input" name="categoryFil[]" type="checkbox" value="1" class="categoryFil" id="catShoes" <?= ($isShoes == 1) ? "checked" : ""; ?>>
            <label class="form-check-label" for="catShoes">Shoes</label>
        </div>
        <div class="form-check">
            <input class="form-check-input" name="categoryFil[]" type="checkbox" value="2" class="categoryFil" id="catPants" <?= ($isPants == 1) ? "checked" : ""; ?>>
            <label class="form-check-label" for="catPants">Pants</label>
        </div>
        <div class="form-check">
            <input class="form-check-input" name="categoryFil[]" type="checkbox" value="3" class="categoryFil" id="catShirts" <?= ($isShirts == 1) ? "checked" : ""; ?>>
            <label class="form-check-label" for="catShirts">Shirts</label>
        </div>
    </div>

    <div class="dropdown-divider"></div>
    <input type="submit" class="button_primary" name="applyFilter" value="Apply">
</form>

Answer №2

When it comes to checkboxes, they are known for their two distinctive states: checked and unchecked.

If you want to determine the state of a checkbox, simply complete these steps:

Start by choosing the checkbox through a DOM technique like getElementById() or querySelector(). Next, check the checked property of the checkbox element. If the checked property is true, then the checkbox is in a checked state; otherwise, it remains unchecked.

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

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

The usage of the "this" keyword in a function call is not

When I try to call a local function using the this pointer, I encounter an error message stating 'Uncaught TypeError: undefined is not a function'. The issue arises on line this.createtimetable(); within the loadtimetable function. The relevant ...

How can I create a cube with complete beveling using Three.js?

I'm struggling to create a beveled cube in my project. I have come across the THREE.ExtrudeGeometry snippet in the documentation here. However, when I tried it out, I only managed to achieve beveled sides on the top and bottom faces like this: https: ...

Exploring the power of Mongoose.js and using the query object with Regular Expressions

In an application focused on locomotives, the search functionality queries models with specific metadata. To check against the keywords field, I need to include a regexp engine. My current approach is as follows: this.keywords = strings.makeSafe(this.par ...

Utilizing Google Apps Script to update files with GitLab's v4 API

I am attempting to modify a specific file in my GitLab repository using the v4 API combined with Google Apps Script. According to the information provided here, the payload needs to be included in the URL. However, I am encountering an issue where Google ...

Encountering CROS Error persistently despite including a header in Node.js for AngularJS

Currently attempting to work with REST API in NODE JS for Angular JS. Despite adding the cors header in my server code, I continue to encounter the error message: XMLHttpRequest cannot load . Request header field Access-Control-Allow-Origin is not allowed ...

Leverage the event manager to automatically reload the page upon detecting a specific string

I currently have this code in place to update a codebox on the page with data retrieved from dyntask.php. <script type="text/javascript"> if(typeof(EventSource)!=="undefined") { var eSource = new EventSource("dyntasks.php ...

Obtaining UTC dates with JavaScript: A guide

Can someone help me figure out how to retrieve the current UTC date using Javascript? I see there are methods available for getting the time in UTC, such as: date.getUTCHours(); But how can I specifically obtain the date? ...

What are the steps to customize the appearance of a folder in the web browser?

Is it possible to customize the presentation of folder contents dragged into Chrome using CSS, HTML, JavaScript, or other methods? I've heard about the HTML5 file API but not sure if that's applicable in this scenario. I think it would be intere ...

Looking for a solution to dynamically fill a list in JQuery with data from a JSON file. Any suggestions for troubleshooting?

Currently, I am utilizing a JSON file to fetch Quiz questions. In my approach, each question is being stored in an array as an object. The structure of the question object includes 'text' (the actual question), 'choices' (an array of po ...

Where is the optimal location for placing a JavaScript listening function within an Angular component?

Summary: Incorporating a BioDigital HumanAPI anatomical model into my Angular 5 application using an iFrame. The initialization of the API object is as follows: this.human = new HumanAPI(iFrameSrc); An important API function human.on(...) registers clic ...

Is there a way to simultaneously update values for all keys within a nested object in react js?

Below is an object where preferences are saved as true/false. I want to update the status for all at once, either setting them all to true or false. obj = { a:false, b:{ c:{ e:{ f:false, g:true, ...

Trigger a function in jQuery when the DOM undergoes changes

Up until now, I have been utilizing livequery which has served its purpose. However, it tends to slow down the page browsing experience, so I am in search of an alternative solution. I have a function that performs ajax on elements with a specific class l ...

ng-class causing delay in setTimeout execution until form is modified

In my JavaScript code, I have implemented a timeout function: setTimeout(function () { $scope.shadow = 'speller-blue'; currIndex = Math.floor(Math.random() * 2); $scope.currCard = cards[currIndex]; }, ...

What specific checks and alerts are triggered by React.StrictMode?

When utilizing React.StrictMode and React.Fragment, according to the React documentation: Both Fragment and StrictMode do not display any visible UI. Instead, they trigger additional checks and warnings for their child components. Question: What specif ...

(Express) Passing data between functions within express.Router().get

What is the best way to transfer a value from one function to another within a router.get method? router.get('/someurl', (req, res, next) => { const token = req.headers.authorization.split(' ')[1] //jwtToken const jwt = jwt.verify( ...

I am currently facing an issue with retrieving the class value that is being generated by PHP code

I am currently facing an issue with jQuery and PHP. Whenever I attempt to target the click event on the class ".id_annonce" in the dynamically generated PHP code, it doesn't retrieve the exact value of what I clicked. Instead, it always gives me a fi ...

Unexpected syntax error encountered when shutting down the route, unable to recover

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.get('/split/name', (req, res) => ...

Unique custom CSS and meta tag options for enhancing iPad/iPhone user experience

Currently, I am developing a web application that integrates Extjs components, PHP, and MySQL. My main goal is to ensure that my application looks correct on the iPad. Are there any specific CSS rules or meta tags that I should be implementing for optima ...

retrieve a value from an eventListener embedded within a forof iteration

How do I pass the coin object returned from the displayCurrencies function to the getCoinId function as a parameter for making an API call to retrieve specific coin data? This is the function created to return the value: let returnID = (value) => { r ...