Using Javascript to access the index of an element that has been checked and

I am working on a dynamic feature that involves a JavaScript variable called 'options'. This variable is designed to store and update a string with the .innerHTML content of every checkbox checked by the user. For instance, if the user checks Instagram and Google+, 'options' will display Instagram, Google+.

Below is the HTML structure:

<section id="extra-features">
    <div class="span3">
        <label class="checkbox" for="Checkbox1">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Instagram
        </label>
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Review site monitoring
        </label>
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Google+
        </label>
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> LinkedIn
        </label>
    </div>

    <div class="span3">
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Pinterest
        </label>
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> FourSquare
        </label>
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Tumblr
        </label>
        <label class="checkbox">
            <input type="checkbox" class="sum" value="50" data-toggle="checkbox"> Advertising
        </label>
    </div>
</section>

<div class="card-charge-info">
    Your card will be charged $<span id="payment-total">0</span> now, and your subscription will bill $<span id="payment-rebill">0</span> every month thereafter. You can cancel or change plans anytime.
</div>

The JavaScript code snippet is as follows:

var price = 0,
    additional = 0,
    options = "",
    inputs = document.getElementsByClassName('sum'),
    total  = document.getElementById('payment-total'),
    total2 = document.getElementById('payment-rebill');

for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var add = this.value * (this.parentNode.className.split(" ").indexOf("checked") > -1 ? 1 : -1);
            additional += add
            total.innerHTML = price + additional;

        if (price == select.options[2].value) {
            total2.innerHTML = 0;
        }
        else {
            total2.innerHTML = price + additional;
        }
    }
}

Access the JSFiddle link here: http://jsfiddle.net/rynslmns/LQpHQ/

Answer №1

If you want a better approach, consider tabulating the data whenever the check state changes. The current method is causing issues where you start at 0 but end up in negative total price territory soon after toggling a few options.

In addition, managing options as a string may lead to complications. It might be more efficient to use an array for easier additions and removals (especially if you tabulate everything at the end).

Here's an example:

var inputs = document.getElementsByClassName('sum'),
    total  = document.getElementById('payment-total'),
    total2 = document.getElementById('payment-rebill');

function sumItUp(){
    var ttl = 0, additional = 0, options = [];
    for (var i = 0; i < inputs.length; i++){
        if (inputs[i].checked){
            options.push(inputs[i].parentNode.textContent.trim());
            var n = new Number(inputs[i].value);
            if (!isNaN(n)) additional += n;
        }
    }
    total.innerHTML = ttl.toFixed(2);
    total2.innerHTML = (ttl + additional).toFixed(2);
    alert('Options:\n\n' + options.join(', '));
}

for (var i = 0; i < inputs.length; i++){
    inputs[i].addEventListener('change', sumItUp);
}

if (!String.prototype.trim){
    String.prototype.trim = function(){
        return this.replace(/^\s+|\s+$/g,'');
    };
}

Check out the jsFiddle here

Answer №2

To retrieve the text of a checkbox, using .innerHTML won't work since checkboxes do not contain any visible text. In this case, you can utilize .nextSibling instead. An example implementation might look like this:

var price = 0,
additional = 0,
options = "",
inputs = document.getElementsByClassName('sum'),
total  = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');

for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var text = this.nextSibling.nodeValue;
        if(options.indexOf(text) != -1) {
            options += text + ',';
        }
    }
}

It is important to also account for scenarios where a checkbox is unselected.

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

What advantages does incorporating "function() 'use strict'" into each individual file provide?

As I dive into revamping an older AngularJS 1.3 project, one striking observation is the consistent pattern of starting each AngularJS code file with: (function () { 'use strict'; angular.module('app').factory('Employees', ...

Dimensions in Material UI

As I embark on my journey with Material UI components for React, I am facing the challenge of integrating pre-styled components into my project. I have noticed that some components appear too large in my layout due to excessive padding and margins. Curren ...

Extract data from Billboard Hot 100 Artist Singles History using BeautifulSoup

I'm attempting to scrape the data from an artist's billboard page regarding their singles and their performance. I'm trying to modify a solution I found elsewhere... It works well until I reach the "peak pos" column. I'm unsure of how t ...

Surprising outcome caused by introducing a service dependency within another service in Angular 6

In my current project, I am facing an issue with ngrx-store and Angular 6. Unfortunately, I cannot replicate the problem on the stackblitz, so I will explain it here. I have a Service1 being used in the component, as well as a Service2 that is used within ...

What is the best way to showcase an array of objects in a table using AngularJS that updates

My technology stack includes angular.js for the front-end, node.js for server-side operations, and PostgreSQL for managing my database. Currently, I have a list of values stored in the database: https://i.sstatic.net/TuO6B.png Upon checking the controll ...

Execute jQuery's .one() function only when in the viewport

As I work on creating a progress bar that plays when in viewport, I've encountered a hiccup. The code executes every time and ends up generating multiple progress bars instead of running just once. The following code snippet is part of a Joomla Extens ...

Inspecting the options within a dropdown menu to adjust a styling attribute

I am in the process of developing a website that features multiple select options for creating sentences. My goal is to detect when users are changing these options to form specific sentences, such as changing "I", "Am", "Blue" to reflect the color blue. T ...

The battle between Hover, Focus, and Blur modes intensifies

My goal is to implement 4 different effects on an element: When hovering over the element. When moving away from the element. When focusing on the element. When blurred. However, I'm encountering a conflict where when I focus on the element, the ...

Adding a Click class can cause significant disruption to the entire CSS layout

I am facing an issue with transforming the X position and appending an additional class to create a slide effect in React. It seems to be working differently compared to using vanilla JavaScript. Below is the code snippet: .inputModal { position: absolut ...

Is there a way to create a Captcha image from text using JavaScript in an HTML document?

As I work on creating a registration web page, ensuring security is key. That's why I'm looking for a way to generate captcha images for added protection. Any suggestions on how I can transform text into captcha images? ...

I attempted to separate a string containing <br> tags using the explode function, but the method was not successful

In my code, there is a string that looks like this <br> ACCEPT:YES <br> SMMD:tv240245ce <br> This string is stored in a variable called $_session['result'] My task is to extract the following information either as an array or ...

Objects array - does not support the 'push' function

In my code snippet, it looks like this: var result = {}; for (var i = 0; i < questions.length; i++) { if(result.hasOwnProperty(questions[i].group)) { var questionsInGroup = result[questions[i].group]; log.debug(typeof questionsInGroup); ...

Unable to use OrbitControls with Node 12's ES6 import functionality

Currently, I am working with Node 12 (experimental-modules) and using npm for three.js. However, I'm facing issues with Imports when trying to include OrbitControls.js in my project. My index.js file is set as "script: module". Unfortunately, none of ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Employ the responseText property of $.ajax() to assign the data to a variable in JavaScript

Despite encountering numerous questions related to my issue, I have been unable to find a suitable answer. In an external JS file, I need the value of a session variable (view_mode) which can be either "complex" or "simple". My goal is to determine which ...

Tips for creating read-only checkboxes with multipledropdown.js in Angular.js

I am trying to make all checkboxes in a multiple dropdown list readonly using Angular.js with the multipledropdown.js plugin. My code snippet is as follows: <div class="col-md-6" ng-show="sub_sub_menu"> <div class="input-group bmargindiv1 col-md- ...

Eliminating unique phrases from text fields or content sections with the help of jQuery or JavaScript

I'm currently working on a PHP website and have been tasked with the responsibility of removing certain special strings such as phone numbers, email addresses, Facebook addresses, etc. from a textarea that users input data into. My goal is to be able ...

Following a Node/Npm Update, Sails.js encounters difficulty locating the 'ini' module

While developing an application in Sails.js, I encountered an authentication issue while trying to create user accounts. Despite my efforts to debug the problem, updating Node and NPM only resulted in a different error. module.js:338 throw err; ...

Error: The call stack exceeded the maximum size due to an unidentified cause

Just a quick note: I managed to fix the issue by now, but I'm curious to understand why it occurred initially: I've been working on retrieving data from mongoDB using mongoose. The code was running smoothly 99% of the time, but for some reason, ...