Steps for generating a jQuery script to tally the checkboxes that have been ticked

[2]. In my quest to implement a checkbox functionality using jQuery, I have composed the following code snippet:-

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Check Box using jQuery</title>
</head>
<body>

<form id="form">
            <input type="checkbox" id="red" name="red" value="Red"/>Red
            <input type="checkbox" id="green" name="green" value="Green"/>Green
            <input type="checkbox" id="blue" name="blue" value=" Blue"/>Blue
            <input type="checkbox" id="black" name="black" value="Black"/>Black<br/>
 </form>

<div id="result">0 boxes are checked</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="chkbox.js"></script>

</body>
</html>

However, despite putting in effort into crafting the chkbox.js script as follows, the functionality is not being executed successfully:-

$(document).ready(function(){
   var $checkboxes=$('#form td input[type="checkbox"]');
   $checkboxes.change(function(){
       var ccc=$checkboxes.filter(':checked').length;
       $('span').text(ccc);
   });
});

I am currently facing challenges determining why this code does not seem to be functioning correctly.

Answer №1

Initially, the absence of a td element within the #form element is noted. Additionally, there is an attempt to display content within a non-existent generic span. A suggested alternative approach would be:

<form id="form">
  <input type="checkbox" id="red" name="red" value="Red" /> Red
  <input type="checkbox" id="green" name="green" value="Green" /> Green
  <input type="checkbox" id="blue" name="blue" value=" Blue" /> Blue
  <input type="checkbox" id="black" name="black" value="Black" /> Black
</form>
<div id="result">No boxes are checked</div>

Regarding your javascript code:

$(document).ready(function() {
  var $checkboxes = $('#form input[type="checkbox"]');
  $checkboxes.change(function() {
    var nr = $('#form input:checked').length;
    var message =  (nr === 0)?'No':nr;
    message += (nr === 1)?" box is checked":" boxes are checked";
    $('#result').text(message);
  });
});

It is advisable to further explore jquery, javascript and html for better understanding.

Answer №2

Your code is missing tds or spans. Here's a simple example to demonstrate:

$('#form input.checkbox').click(function(){
  $('#result').text($('#form input.checkbox:checked').length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form">
   <input type="checkbox" class="checkbox" id="red" name="red" value="Red"/>Red
   <input type="checkbox" class="checkbox" id="green" name="green" value="Green"/>Green
   <input type="checkbox" class="checkbox" id="blue" name="blue" value=" Blue"/>Blue
   <input type="checkbox" class="checkbox" id="black" name="black" value="Black"/>Black<br/>
 </form>

<div><strong id="result">0</strong> boxes are checked</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

Incorrectly loading static images in React SSR

I am currently working on a React SSR app and my folder structure looks like this: https://i.sstatic.net/RA2H2.png My static express middleware successfully handles static files and images in the tag on the client side: https://i.sstatic.net/Zhzf2.png ...

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

Tips for utilizing code submitted by a user to extract meaningful errors

As I work on developing a mod for the online game Cookie Clicker, I've implemented a feature that allows users to input their own code to enhance the functionality of my mod. However, before users save their code using my custom editor, I want to run ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

Organize Image Collection in an Asp.Net MVC Webpage

Looking to build an Asp.Net MVC 5 (Razor) view and controller that can manage a collection of images. Consider a model similar to the following (where the data is stored in a database and accessed using EF): public class Game { public Guid Id {get; se ...

Enhance the efficiency of synchronized horizontal scrolling using React/Redux to boost overall performance

I'm currently working on creating a grid with synchronized horizontal scrolling across different sections (such as a header and multiple table sections below). Each section should scroll together horizontally, maintaining synchronization using a redux ...

Is it acceptable to utilize the "sticky-top" class in a mobile-friendly navigation bar?

I'm facing an issue with implementing the Sticky-top function on a navbar within a Django project. The navbar is responsive and can be expanded by clicking a button, but I want it to remain fixed at the top when the user scrolls down. Currently, I am ...

Deleting the HTML element

Can someone assist me with my script issue? I am facing a problem: when I open my file on fullscreen (over 768px), and move my pointer around the logo div, nothing happens. However, if I resize my browser to below 768px, then back again above 768px, the ...

To achieve proper display of multiple boxes, it is essential for each box to be

My current approach involves adding boxes to the scene based on specific dimensions for height, width, and depth, and it works perfectly when the boxes are all square. https://i.sstatic.net/HdDSX.png However, the issue arises when I try to use a rectangu ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Having trouble with CSS last-child selector not functioning properly with nested divs?

I was in the process of designing my personal website with Bootstrap, focusing specifically on the resume section where I am implementing a vertical timeline to showcase my experiences. For the final experience in each section, I wanted to adjust the line ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

Obtaining a unique diamond pattern overlay on my Google Map

Currently, I am integrating Vue.js with vue-google-maps, and I have noticed a diamond-shaped watermark appearing on the map. After reaching out to Google support, they mentioned that this issue is specific to my tool, indicating it might be related to eith ...

Establishing a recurring interval when the component mounts for a specified period of time

I have read through several Q&As on this topic, but I am still unable to pinpoint what mistake I am making. The code snippet below is meant to display a countdown in the console and update the DOM accordingly, however, it only prints 0s in the console ...

Tips for activating swf file autoplay on the mobile edition of WordPress

I recently added a swf file to my WordPress page (https://www.pacifictintlv.com/mobile). However, I have noticed that it does not seem to work properly when viewed on mobile devices. Is there a way to redirect users to the Flash download link if they do ...

Unable to display PNG file on HTML document

Hi there, I'm having a bit of trouble adding a logo to my website. Initially, I had a sample logo that worked perfectly fine. Here's the code snippet: <a class="navbar-brand d-flex align-items-center" href="/"> <a ...

Prevent unnecessary re-renders of components by optimizing state changes with hooks

In my Layout component, there is a Table component with an Entry component for each row. Each row can be selected, and when a row is selected, it is added to the state so that all selected entries can be sent to a REST service later using a button. The i ...

Ways to invoke a class method by clicking on it

My initialization function is defined as follows: init: function() { $("#editRow").click(function() { <code> } $(".removeRow").click(function() { <code> } } I am trying to find a way to call the class method removeRow directly in the onc ...

The JSON information is not appearing as expected

Utilizing a jQuery function, I am attempting to access a JSON file: $.ajax({ type: 'GET', url: '/data/coffee.json', dataType:'json', success: function(data) { let widget = displayData(data); $(" ...

Launching a segment from a different page within a foundation reveal modal

With the goal of displaying a modal that contains content from a section on another page when a link is clicked, I encountered a specific issue. For instance: <a href="/otherpage" data-reveal-id="myModal" data-reveal-ajax="true"> Click Me For A Mod ...