Validation for checkbox completeness is not functioning as expected

I am attempting to create a function that checks if all checkboxes are checked and then changes the class of a button accordingly. However, my code does not seem to be functioning as expected and I am unsure why.

<input type="checkbox" id="check1" onchange="checkIfChecked();" class="checkThis" value="check 1"> Check 1<br />
<input type="checkbox" id="check2" onchange="checkIfChecked();" class="checkThis" value="check 2"> Check 2<br />
<input type="checkbox" id="check3" onchange="checkIfChecked();" class="checkThis" value="check 3"> Check 3<br />
<input type="checkbox" id="check4" onchange="checkIfChecked();" class="checkThis" value="check 4"> Check 4<br />
<input type="checkbox" id="check5" onchange="checkIfChecked();" class="checkThis" value="check 5"> Check 5<br /><br />
<a href="#" style="width:190px;display:block;" id="absenden" class="button-theme-disable">
    <span class="span_outer">
        <span class="span_right">
            <span class="span_left">
                <span style="width: 182px;" class="span_inner">Save & Close</span>
            </span>
        </span>
    </span>
</a>
    function checkIfChecked() {

    if ($('.checkThis input[type="checkbox"]').not(':checked').length == 0) {
        $('#absenden').removeClass('button-theme-disable');
        $('#absenden').addClass('button-theme');
    } else {
        $('#absenden').removeClass('button-theme');
        $('#absenden').addClass('button-theme-disable');
    }

};

Here is a demo: https://jsfiddle.net/bt35r2tc/1/

Can anyone spot what mistake I might have made?

Answer №1

.checkThis is a checkbox itself. To select the checkbox within .checkThis, use

.checkThis input[type="checkbox"]
. You can try it like this:

function checkIfChecked() {
    if ($('.checkThis').not(':checked').length == 0) {
        $('#absenden').removeClass('button-theme-disable');
        $('#absenden').addClass('button-theme');
    } else {
        $('#absenden').removeClass('button-theme');
        $('#absenden').addClass('button-theme-disable');
    }
}

Full Code

function checkIfChecked() {
  if ($('.checkThis').not(':checked').length == 0) {
    $('#absenden').removeClass('button-theme-disable');
    $('#absenden').addClass('button-theme');
  } else {
    $('#absenden').removeClass('button-theme');
    $('#absenden').addClass('button-theme-disable');
  }
}
/* Disable Theme */
.button-theme-disable .span_outer .span_right {
  background: url(http://mirsoftware.de/daniel/buttonrechtsdisable.png) no-repeat scroll right center;
  text-decoration: none;
  height: 22px;
  display: block;
}

... (CSS code truncated for brevity) ...

.button-theme:hover .span_outer:hover .span_inner:hover {
  background: url(http://mirsoftware.de/daniel/buttonmittemo.png) repeat-x scroll 0 0;
  text-decoration: none;
  cursor: pointer;
  color: White;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" onchange="checkIfChecked();" class="checkThis" value="check 1"> Check 1
<br />
<input type="checkbox" id="check2" onchange="checkIfChecked();" class="checkThis" value="check 2"> Check 2
<br />
... (more input checkboxes and code truncated for brevity) ...
<a href="#" style="width:190px;display:block;" id="absenden" class="button-theme-disable">
    <span class="span_outer">
        <span class="span_right">
            <span class="span_left">
                <span style="width:182px;" class="span_inner">Speichern & Schließen</span>
            </span>
        </span>
    </span>
</a>

Answer №2

What is the rationale behind not utilizing each in Jquery in this manner:

$(".checkThis").each(function(){
     if($(this).is(":checked")){     
         //checkbox is checked
     }else{
        //checkbox is not checked
     }
});

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

Searching and categorizing information within a table using jQuery

Can someone help me with merging my html and jquery code for type and filter table data, as well as tag data in the same input box? I have the code for both functionalities separately (http://jsfiddle.net/tutorialdrive/YM488/), but I want to combine them. ...

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

The retrieval of JSON data in a JavaScript function is malfunctioning

I am new to working with Ajax and have reached the point where I am able to retrieve data. However, I am struggling to return the data as I keep getting undefined values. Below is the code snippet: function select_aragement(arragament){ var arrst = ar ...

Getting inaccurate results by entering numbers

const [shipping, setShipping] = useState({ overseas: '3' }) const handleChange = (e) => { setShipping({ overseas: e.target.value }) //can change to 8 or 3 } const selection = shipping.overseas console.log(sel ...

Is there a way to dynamically import images in Next JS without having to place them in the public folder?

Currently, I am developing a textbook website in which authors contribute textbook folders containing markdown files and images: textbooks ├───textbook-1 │ ├───images │ └───markdown-files └───textbook-2 ├── ...

The color of the links in the Bootstrap navbar refuses to budge

I'm having trouble changing the color of my navbar links to white and spacing them out evenly. I've written some code to do this, but for some reason, it keeps getting overridden. The background of the navbar is an image, and when I remove the im ...

Tips for managing the velocity of JavaScript navigation scrolling

Hey everyone, I recently discovered this incredibly helpful JavaScript sticky side navigation script and it works like a charm! However, since I don't know much about JS, I was wondering if there's a way to slow down the scrolling speed? functio ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

Are you experiencing issues with the AJAX auto-suggestion system displaying duplicate entries?

I've implemented a search bar on my website that allows users to search for specific titles. To enhance the user experience, I added an auto-completion feature using a simple MySQL table with suggested completions. Here's an image of the setup: ...

Utilizing SVG and CSS together: Implementing clip-path in a flexbox layout

This task may seem simple to some, but I am struggling to mask an image with an SVG graphic. I have created an SVG with the clipPath element: <svg id="heart-path-container" version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 ...

Guide on transferring a WordPress website to a new domain

I manage a WordPress blog on my main domain, but I am looking to duplicate the entire blog onto a secondary "dummy" domain so I can experiment with significant changes without impacting my primary domain. My main domain is and my dummy domain is Althoug ...

Sprockets::FileNotFound - unable to locate the file named 'query.effects.core'

Whenever I try to access localhost:3000 after starting my Rails server, I keep encountering a "file not found" error. The specific message says couldn't find file 'jquery.effects.core'. Despite trying various solutions like pulling a fresh c ...

What is the best way to reload DataTables using an ajax/error callback?

In my code, I am customizing the default settings of DataTables like this: $.extend(true, $.fn.dataTable.defaults, { lengthChange: false, deferRender: true, displayLength: 25, stateSave: false, serverSide: true, processing: true, ...

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

I am looking to eliminate any special characters from a designated section of a string using Javascript

I have a string that looks like this: var myString = '{"key1":"value1", "key2":"value2", "key3":"value3"}'; My objective is to remove double quotes and other special characters only from value3. Sometimes the string may look like: var myStrin ...

Creating a direct connection between a parent node and all of its children in OrgChartjs

Can I connect all children directly to one parent in Balkan OrgChart.js? This is my starting point based on the documentation of OrgChart.js. window.onload = function () { OrgChart.templates.family_template = Object.assign({}, OrgChart.templates.ana); ...

Ways to induce scrolling in an overflow-y container

Is there a way to create an offset scroll within a div that contains a list generated by ngFor? I attempted the following on the div with overflow-y: @ViewChild('list') listRef: ElementRef; Then, upon clicking, I tried implementing this with s ...

403 Malicious Path Middleware Error in Express.js

Encountering an error when sending a post request to my server, but only on the production server - whereas the staging server is functioning properly. Both servers are hosted on AWS Ubuntu instances. Investigating the stack trace, it appears that the err ...

The UI gets all wonky when using ThemeRoller for jQuery

Currently, I am encountering an issue where I want to utilize ThemeRoller for implementing custom themes on my views. However, when I apply these themes, the interface ends up looking distorted, as shown in the images below: Before using ThemeRoller: Aft ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...