Disable button not necessary when validating checkboxes

I'm working on a simple function that involves 3 checkboxes. The goal is to disable the button if all checkboxes are unchecked, and enable it only when all three checkboxes are checked.

   function checkAll() {
     var checkbox1 = document.getElementById("ch1");
     var checkbox2 = document.getElementById("ch2");
     var checkbox3 = document.getElementById("ch3");
     var submitBtn = document.getElementById("btn");

    if (checkbox1.checked && checkbox2.checked && checkbox3.checked){  
    return submitBtn.disabled = false;
        
  }
  else {
    return submitBtn.disabled = true;
}
   }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>
    <input type="checkbox" id="ch1" >
    <input type="checkbox" id="ch2" >
    <input type="checkbox" id="ch3" >
    <button onclick="checkAll()" id="btn">Submit</button>
</body>
<script>


</script>
</html>

Answer №1

To ensure functionality, it is necessary to attach an EventListener to the checkboxes and monitor any changes in their state rather than embedding the script within a button itself:

let checkboxes = document.querySelectorAll('input[type="checkbox"]');

checkboxes.forEach(el =>
  el.addEventListener('change', function() {
    let checked_checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
    if (checked_checkboxes.length === checkboxes.length) {
      document.querySelector('#btn').removeAttribute('disabled');
    } else {
      document.querySelector('#btn').setAttribute('disabled', true);
    }
  })
)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>
    <input type="checkbox" id="ch1" >
    <input type="checkbox" id="ch2" >
    <input type="checkbox" id="ch3" >
    <button onclick="sub()" id="btn" disabled>Submit</button>
</body>
<script>


</script>
</html>

Answer №2

To disable your button, you must use a boolean value. The problem lies in how you are interpreting this.checked.

btn.disabled = false;

In addition, if the button is enabled, it will simply be disabled and not rechecked. You should trigger the sub() function on checkbox click.

function sub() {
  var a = document.getElementById("ch1");
  var b = document.getElementById("ch2");
  var c = document.getElementById("ch3");
  var btn = document.getElementById("btn")

  if (a.checked == true && b.checked == true && c.checked == true) {
    btn.disabled = false;
  } else {
    btn.disabled = true;
  }
}
<input onclick="sub()" type="checkbox" id="ch1">
<input onclick="sub()" type="checkbox" id="ch2">
<input onclick="sub()" type="checkbox" id="ch3">
<button id="btn" disabled>Submit</button>

Answer №3

const checkboxesChecked = () => {
  document.getElementById("ch1").checked = true;
  document.getElementById("ch2").checked = true;
  document.getElementById("ch3").checked = true;
  let checkedCount = 3;
  const allCheckboxes = document.querySelectorAll("input[name=checkbox]");
  
  allCheckboxes.forEach(function(checkbox){
    checkbox.addEventListener('change', function() {
      if (this.checked) {
        console.log("Checkbox is now checked.");
        checkedCount++;
        console.log(checkedCount);
      } else {
        console.log("Checkbox is no longer checked.");
        checkedCount--;
        console.log(checkedCount);
      }
    
      if(checkedCount < 3){
        document.getElementById("btn").disabled = true;
      } else {
        document.getElementById("btn").disabled = false;
      }
    });
  });
}

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

Jupyter QtConsole: Customize default CSS by selecting from built-in options in the configuration settings

I am currently using Jupyter on a Windows platform and I am looking to customize the coloring of the QT console. Is there a way to set a default CSS style through a configuration file without having to manually specify it every time? Instead of passing t ...

Unusual css glitch observed when hovering over a span/link

Currently, I'm struggling with a CSS code issue. My goal is to have the div #hidden show when someone hovers over the link in #trigger. <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> ...

Tips on how to update a table following each button click during an ajax request

I am encountering an issue while trying to display data in a table by clicking on a search button. The problem arises when there is no data between the specified "Fromdate - Todate" range; the error message appears correctly. However, even after entering t ...

What is the process for adjusting the attribute of a subitem utilized by the `use` element?

Currently, I am studying SVG and have a question about changing the circle fill value of the second use element. Here is what I have tried: * { stroke: brown; stroke-width: 1; fill: none; } .canvas{ border-color: green; border-style: solid; border-widt ...

Creating a dynamic overlapping image effect with CSS and JavaScript

My fullwidth div has an image that overlaps it. When the browser is resized, more of the image is either shown or hidden without resizing the actual image itself. I managed to get this effect for the width, but how can I achieve the same result for the hei ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

The validity of AngularJS form is constant and always returns true with formName.$valid

I am facing an issue with my Angular application form where even though the input fields are blank, formName.$valid is always true. Below is the HTML code for my form: <form name="contactForm" novalidate ng-submit="processForm(formData)" autocomplete=" ...

Ever since I upgraded my three.js, my code seems to have lost its functionality

I encountered an issue while transitioning from three.js version r58 to r73. The code that previously displayed the model perfectly is now failing to render the model. Despite detecting the mesh in the debug window, the model remains invisible on the scree ...

Is it possible for a for loop to execute console.log() immediately for each cycle while the remaining part of the loop continues

As a newcomer to Selenium and Nodejs, I am in the process of understanding why console.log() appears to be asynchronous within my for loop. It is puzzling to me why all the console log lines are printed immediately to the console, even though the overall f ...

What is the best way to manage the package-lock.json file during deployment from git using SSH?

In my deployment process, I utilize a Git repository to check code in. By using web hooks, a deployment script is triggered on the production server. Once connected to Git via SSH and a .pem key on the server, I perform a Git pull, npm install, webpack bui ...

Disable the checkbox functionality in Angular

Is there a way to disable clicking on a checkbox while still keeping an ng-click function attached? <input id="record-2" type="checkbox" class="checkbox" ng-click="doIfChecked()"> I've tried using ng-readonly and ng-disabled, as well as css p ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

"JavaScript throws an 'Undefined' error when trying to access a basic

I am struggling with a basic set of HTML and JS files that are not functioning properly, and I can't seem to pinpoint the issue: <html> <head> <script type="text/javascript" src="data.json"></script> < ...

Ways to avoid multiple AJAX requests in PHP interfering with one another when updating the database

I am facing an issue with a JavaScript client that sometimes sends two AJAX requests to the server within milliseconds of each other. Unfortunately, I have no control over fixing this bug on the client side and can only handle it from the server side. The ...

Prevent cross-site scripting vulnerabilities by replacing the characters "'<'" and "'>'"

Is it possible to protect my website from XSS attacks by simply replacing < and > with &lt; and &gt;, or is there more to consider? For example: <?php echo '<div>' . $escaped . '</div>' ?> I am alread ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

What is the best method for playing raw audio wav files directly in a web browser?

I'm currently attempting to play wav raw data in the browser that is being transmitted from a Node.js server via socket.io. The main goal is to play the receiving data as quickly as possible without waiting for all the data to be received. I initially ...

Having difficulty handling text overflow in Angular4 and HTML

I'm facing an issue with displaying a very large text in a table. Despite trying various attributes such as - { text-overflow: clip; } { text-overflow: ellipsis; } { text-overflow: ellipsis-word; } { text-overflow: "---"; } { text-overflow: ellip ...

Looking for assistance with converting a basic script into a Joomla 2.5 module and resolving issues with Java integration

I'm having issues with my code in Joomla 2.5. It seems like the Java function is not functioning properly within Joomla. Can someone assist me with troubleshooting this problem? mod_mw_pop_social_traffic.php <?php defined( '_JEXEC' ) or ...

Having trouble retrieving a customized header from the HTTP response

I've encountered an issue with my Node.js server where I set a custom header. I added the Access-Control-Expose-Headers to allow access from browsers, and it works fine in Chrome and Firefox. However, I'm getting an error in PhantomJS saying "Ref ...