Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distribution varies based on how many checkboxes are checked - if all 3 are checked, each receives 33%; if two are checked, they get 50% each; and if only one is checked, that checkbox gets 100%. I have been struggling with implementing this functionality as I primarily focus on the appearance of the checkboxes rather than their values. My JavaScript skills are limited, which makes it difficult for me to find a suitable solution. Currently, I have hard-coded values in a JSFIDDLE:

JSFIDDLE

<td>
  <input type="checkbox" name="1_1" class="checkbox" checked id="11" value="on" >
  <label for="11">1</label>
  <span id="Result"></span>
</td>
<td>
  <input type="checkbox" name="1_X" class="checkbox"checked id="1X" value="on">
  <label for="1X">X</label>
  <span>33%</span>
 </td>
 <td>
  <input type="checkbox" name="1_2" class="checkbox" checked id="12" value="on">
  <label for="12">2</label>
  <span>33%</span>
</td>

window.onload = function () {
var input = document.querySelector('input[type=checkbox]');

  function check() {
    var p = input.checked ? "100" : "0";
    document.getElementById('result').innerHTML = p+'%';
  }
input.onchange = check;
check();
}

Answer №1

To resolve the issue, I utilized Jquery and implemented a handler on the checkbox to keep track of the checked inputs.

$("input[type=checkbox]").click(function(){
    var arrayId=$(this).attr("name").split("_");
    var numberId=arrayId[0];
    var percentage=Math.floor(100/$("input[name*='"+numberId+"_']:checked").length);
    console.log(percentage);
    $("input[name*='"+numberId+"_']").parent().children("span").html("0%");
    $("input[name*='"+numberId+"_']:checked").parent().children("span").html(percentage+"%");
});

Check out the code on JsFiddle:https://jsfiddle.net/xc8xt682/3/

Answer №2

Using vanilla JavaScript instead of jQuery makes the code a little more lengthy, but still functional. LTastys response may offer a better solution, but I wanted to share mine as well since I was working on it at the same time.

const cells = Array.from(document.querySelectorAll('td'));
const calculate = () => {
    const value = ['100%', '50%', '33%'][cells.filter(cell => cell.querySelector('input').checked).length - 1];
    cells.forEach(cell => {
        const span = cell.querySelector('span');
        if (cell.querySelector('input').checked) {
            span.textContent = value;
        } else {
            span.textContent = '0%';
        }
    });
};
cells.forEach(cell => {
    cell.querySelector('input').addEventListener('click', calculate);
});

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

Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Jade console.log() not functioning properly as anticipated

Is it possible that I can just insert -console.log('hello') into any part of the jade code? It doesn't seem to be working, do you know what could be causing this issue? ...

Image carousel with variable height

I'm attempting to implement a slide show of images with previous and next functionality. When the user clicks "previous," I want the images to slide to the left, and when they click "next," I want the images to slide to the right with a 0.5 second del ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...

The predicament encountered with user registration in the realm of Node.js

I am encountering a problem with the sign-up route in node.js and MongoDB. Whenever I attempt to post data using Insomnia, it displays an error message. You can find the screenshot of the error [here](https://i.stack.imgur.com/qnGAv.png). Here is the code ...

What is the process for passing a component as a parameter to a function within a different component?

Within my scenario, I have a series of components '1,2,3,...' imported into another primary component 'A'. Within component 'A', certain operations are performed and a filtered component is then returned from the list of compo ...

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

Using VueMultiselect with Vue 3: A guide for beginners

I'm currently experimenting with the vue multiselect component, but when I include it in the template, I am encountering a series of warnings and errors. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

What could be causing my React components to not display my CSS styling properly?

If you're developing a React application and integrating CSS for components, ensure that you have included the style-loader and css-loader in your webpack configuration as shown below: module.exports = { mode: 'development', entry: &apo ...

Ways to display a variable within an HTML element

What could be causing variable a to be undefined? export default function Surah() { let a; const updateVariable = (id) => { a = id; console.log(a); }; return ( <div> <div> <button onClick={() => ...

React - the elusive nature of variable mutation

In my React app, there is a requirement to choose a specific version of a phone and then confirm the selection. Below is an excerpt from the React component's code: const App = () => { const [selectedVersion, setSelectedVersion] = useState(""); ...

Encountered an issue when attempting to utilize `npm start` within a React JS project following

https://i.stack.imgur.com/yII3C.png Whenever I attempt to run npm start in the vsCode terminal, an error pops up as shown in the image above. In the picture provided, you can see that my package.json only contains a start script. Can anyone offer assistan ...

Collect information from forms and save it to a mobile phone number

Is it possible to forward form field details to a cell phone number via text message? Here is the code I currently have for sending form data to an email address. If any adjustments need to be made, please provide instructions. <?php if(isset($_POST[ ...

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

Executing a function in JavaScript using square brackets

While I was reading through the jQuery source code, I came across this interesting line: jQuery(this)[ state ? "show" : "hide" ](); Is there any particular benefit to using this syntax over the more traditional approach shown below? state ? jQuery(this) ...

Working with AngularJS: binding data to dynamically appended HTML elements using JavaScript

Is there a way to connect an angular event and model to an html element that is added through javascript code? To see my code, click here: https://jsfiddle.net/hq7qk48n/13/ <div ng-app> <div ng-controller="MyController"> <input ...

send additional form elements to the AJAX suggestion box script

** shifted to this location: Numerous similar AJAX suggestion boxes without IDs I enlisted the help of a developer to create a jQuery AJAX suggestion box script some time ago, and it has been working flawlessly. Now, I am striving to understand it better ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...