In order to activate the button, make sure all 3 boxes are checked

Can someone provide some guidance on the script below? I'm utilizing it for a pop-up when a user attempts to add a product to the cart.

Presently, the button will activate if at least one checkbox is selected (although it's not working on fiddle). However, my desired functionality is to have the button disabled until all three checkboxes are checked.

It's important to note that there are two different pop-ups for two distinct brands. For one brand, only one checkbox needs to be checked for the button to activate. But for this second pop-up, there are three checkboxes. Therefore, I need the script to work with one checkbox selected and all three checkboxes checked.

<div>
  <div class="vet-diet-info">

    <p>
      <label>
        <input id="checkbox" type="checkbox"> Agree.
      </label>
    </p>
    <p>
      <label>
        <input id="checkbox" type="checkbox"> Agree.
      </label>
    </p>
    <p>
      <label>
        <input id="checkbox" type="checkbox"> Agree.
      </label>
    </p>
    <p>
      <a id="mainbutton" href="javascript:void(0)" data-dismiss="modal" class="btn btn-info" disabled="disabled">Confirm Purchase</a>
    </p>
  </div>
</div>


function SetVetDietsEventsPopup() {
  jq("#checkbox").off("change").on("change", function() {
    if (this.checked) {
      jq("#mainbutton").removeAttr("disabled");
    } else {
      jq("#mainbutton").attr("disabled", "disabled");
    }
  });
  jq("#btnVetDietsConfirmPurchase").off("click").on("click", function() {
    if (jq(this).is(":disabled")) {
      return false;
    } else {
      RunAddToCartButtonClickEvent();
      return false;
    }
  });
}

https://jsfiddle.net/5xy0qtvy/1/

Answer №1

Initially, it is important to note that the id attribute is unique. It is not possible to assign the same id to multiple elements; instead, use the class attribute.

var totalCheckboxes = $('.checkbox').length; //total number of checkboxes
var checkedBoxes = 0;

$('.checkbox').each(function() {
if ( $(this).prop('checked') ) { 
checkedBoxes++;
}
});

if (totalCheckboxes === checkedBoxes) 
$("#mainbutton").removeAttr('disabled');
else
alert('Please make sure to check all the checkboxes');

Remember to update all instances of id="checkbox" to class="checkbox" throughout the code.

Answer №2

Correction I have rectified the logic where it was previously inverted.

It is important to note that the ID must be unique.

Instead of using the each loop, you can achieve the same result by utilizing the combination of :not and :checked to check for any unchecked boxes.

$(document).ready(function() {
  $(".vet-diet-info [name='checkbox']").click(function() {;
    $("#mainbutton").prop("disabled", $(".vet-diet-info [name='checkbox']:not(:checked)").length !== 0);
    console.log($("#mainbutton").prop("disabled"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="vet-diet-info">

    <p>
      <label>
        <input name="checkbox" type="checkbox">Agree.
      </label>
    </p>
    <p>
      <label>
        <input name="checkbox" type="checkbox">Agree.
      </label>
    </p>
    <p>
      <label>
        <input name="checkbox" type="checkbox">Agree.
      </label>
    </p>
    <p>
      <a id="mainbutton" href="javascript:void(0)" data-dismiss="modal" class="btn btn-info" disabled="disabled">Confirm Purchase</a>
    </p>
  </div>
</div>

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

Display the current count of selected radio buttons in real-time

I am working with radio buttons that are generated dynamically using a 2D array within a while loop. I want to display the number of radio buttons checked when one is clicked. Here are my radio buttons: $n=0; while($row=mysqli_fetch_row($rs)){?> <f ...

Encountering issues loading background image with Reactjs and Webpack

I've encountered an issue while trying to load a background image in my React project from a custom CSS file. I am currently using Webpack 4. .bgimage { height: 100vh; background: url('../images/header.jpg'); } Unfortunately, the image ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

Guide on embedding PHP code into a HTML div element using JQuery

I am having trouble loading PHP code into a div tag to display the results. The code I have listed below does not seem to work for me. If anyone can offer assistance in resolving this issue, I would greatly appreciate it. Here is the code snippet: <h ...

Saving several inputs with incremented values

I'm facing an issue with saving data from multiple input fields in a for loop: <input type="number" name="device_id_1"> <input type="number" name="device_id_2"> ... <input type="number" name="name_1"> <input type="number" name="n ...

Assistance with Javascript Objects Using JSON and AJAX

Currently, I am utilizing Ajax to retrieve data from my Json file. A problem I am facing is that in one particular div of my html, I need to include both a heading and a paragraph. I attempted to create a property like so: "headingpara": "<h1> blah ...

Submitting modal form information using AJAX to PHP

As a novice in the realm of web programming, I find myself seeking some guidance to untangle a riddle. Regrettably, my grasp of the basics still leaves much to be desired. Within my main page, view.adminsettings.php, I've designated a Navigation DIV ...

The add method in jQuery allows you to combine multiple elements

I am currently developing a jQuery plugin that showcases images with a specific class in the middle of the screen. When clicked, the image expands to full size and is surrounded by a gray overlay. Clicking on the overlay should make it disappear. Currently ...

Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code. ACC.payDirect = { _autoload ...

Trying to dynamically filter table cells in real time using HTML and jQuery

During my search on Stack Overflow, I successfully implemented a real-time row filtering feature. However, I now require more specificity in my filtering process. Currently, the code I am using is as follows: HTML: <input type="text" id="search" place ...

Ajax waits for the animation to finish before proceeding

This topic has been previously discussed on stackoverflow, but none of the solutions have helped me solve my issue. I am utilizing the "form" jQuery plugin in the following manner: $(document).ready(function() { $('#myForm').ajaxForm({ ...

Tips for triggering a jQuery click event following an append action within a change event handler

I am facing an issue with my HTML document: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"> <title>Test</title> <script s ...

JQuery Success/Failure Callback does not trigger the function

I'm a beginner with jQuery and I'm trying to use it to call a Python web service and display a message based on the response received. Below is the current jQuery code I have: $(document).ready(function(){ $("#loginForm").submit( function () { ...

In a particular configuration involving Docker and Nginx rewrite rules, there is a notable alteration in URLs that include question marks when utilized in jQuery.ajax calls

My PHP/Laravel app is running smoothly in a dockerized environment using the php:7.4-apache container. During development, we had it accessible through http://localhost:81. Now, our aim is to make this service available at http://localhost/foo/bar within ...

Configuring the remote source for autocomplete suggestions

Similar Issue: Error with jquery autocomplete this.source function I am facing an issue with my autocomplete feature where I am trying to connect it with my API to retrieve customer account numbers. The problem arises when the API response includes mu ...

In Node.js, I encountered an issue where req.body was returning as undefined, despite the fact that when I logged req, I could

I am having trouble logging the req.body to the console in my Twilio text app. When I try console.log(req), the body and its contents show up, but it says that the body is undefined when I try to log it on its own. Any help would be greatly appreciated. ...

What are the steps for utilizing CSS Global Variables?

Hey there, thank you for taking the time to help me out. I'm having a simple doubt that I just can't seem to figure out. So... here's my '/pages/_app.js' file: import '../public/styles/global.css'; export default funct ...

The HTML and JavaScript implementation of the Game of Life is experiencing technical difficulties

I attempted to create my own version of the Game of Life using HTML canvas and JavaScript. With the aid of various online tutorials, I was able to write a piece of code that I am still confident in. However, upon launching the HTML page in the browser and ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

How can I uniquely identify and edit individual cells within an ng-grid using the bgColor property?

I need some clarification regarding Angularjs ng-grid. Is there a way to distinguish between the edit-cell and non-edit-cell in ng-grid? Perhaps using different background colors? ...