How get the sum of all the checkbox values of checked items - javascript

let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function() {
if (addonCheckboxes[i].checked != false) {
priceSection.textContent = parseInt(customProductPricing) + parseInt(addonCheckboxes[i].getAttribute("price"));
} else {
priceSection.textContent = parseInt(customProductPricing)
}
})
}
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
I want to get the total of all the checkboxes if they are all checked. So far it gives only one value. And need to deduct the prices if the checkbox is unchecked.

This one has fixed all the errors you made in your markup, and simplified the code by alot.
const output = document.getElementById('priceSection');
const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);
document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>

You are overwriting instead of summing. When you are iterating through an array of checkboxes and you find that more than one is checked your function fails.
You should firstly count the sum of checked checkboxes and then send it to priceSection, and when your sum is equal to zero you should set it parseInt(customProductPricing) like you did in else.

When the change event of the <input> elements is triggered, the update() method is called and the values in the page are collected and printed on the page. I don't understand the issue of lowering the price if the checkbox is not selected. Update the update() method to subtract unselected values from the total using the following approach; Add an else statement to the if block.
(function() {
let addonCheckboxes = document.querySelectorAll(".custom-checkbox");
function update()
{
let total = parseInt(document.getElementById("customProductPricing").textContent);
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
if(addonCheckboxes[i].checked == true)
total += parseInt(addonCheckboxes[i].value);
document.getElementById("priceSection").innerHTML = "Result: " + total;
}
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
addonCheckboxes[i].addEventListener("change", update);
})();
<input class="custom-checkbox" type="checkbox" value="10"/>
<label>10</label>
<input class="custom-checkbox" type="checkbox" value="20"/>
<label>20<label>
<input class="custom-checkbox" type="checkbox" value="30"/>
<label>30<label>
<!-- Static Value -->
<div id="customProductPricing">40</div>
<br><div id="priceSection" style="color: red;">Result: </div>

Using data set you can access price
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
let sum = 0
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function(e) {
console.log(e.target.dataset.price)
if (addonCheckboxes[i].checked != false) {
sum = sum +Number(e.target.dataset.price)
} else {
sum = sum -Number(e.target.dataset.price)
}
customProductPricing.innerHTML = sum
})
}
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>

As #Sercan has mentioned... I am also not sure about the issue of loweing the sum but I've whipped up something for you.
Hopefully it'll lead you to what you want to achieve.
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing");
var checkboxes = document.getElementsByClassName("custom-checkbox");
function sum(){
var total = 0;
for(let x = 0; x < checkboxes.length; x++){
let price = document.getElementsByClassName(x);
if(price[0].checked){
total = total + Number(price[0].dataset.price);
}
}
console.log('Sum = ' + total)
}
<input class="custom-checkbox 0" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 1" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 2" onclick="sum()" type="checkbox" data-price="150"></input>
<div id="priceSection"></id>
<div id="customProductPricing">"150"</div>

Related

How to search different digits in numbers

I have a function which split the input value on space and I looped through to search them in a number but only the last value is shown (checked) not the other before it .
One solution can be by removing else that way it worked fine but this way when changing the value the checked number remain intact(last searched result are also shown).
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var reader = document.getElementsByClassName("checkbox_inputs")
for (let i = 0; i < reader.length; i++) {
var readerText = reader[i].value
var readerText1 = readerText.trim()
var reed = document.getElementById("allNumbers").value;
var reed1 = reed.trim()
var myDiffValues = reed1.split(" ");
document.getElementById("demo").innerHTML = myDiffValues
if (reed != '') {
for (var item of myDiffValues) {
if (readerText1.indexOf(item) > -1) {
reader[i].checked = true;
} else {
reader[i].checked = false;
}
}
} else {
reader[i].checked = false;
}
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
One strange behavior it is showing is when lot of space is entered in the input all checkboxes get checked
You can make it much more easily :)
Explanation
First of all you read your inputs (checkbox_inputs).
Then you
read just once the numbers (allNumbers) and you can trim and split
in one line.
Last step: for each one of your checkboxes you set the checked value if the allNumbers list includes the expected value. false otherwise.
Working Example
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var inputs = document.getElementsByClassName("checkbox_inputs");
var allNumbers = document.getElementById("allNumbers").value.trim().split(" ");
document.getElementById("demo").innerHTML = allNumbers
for (let i = 0; i < inputs.length; i++) {
inputs[i].checked = allNumbers.includes(inputs[i].value);
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>

Output wont show (javascript)

I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D
You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.

A function that collects an array of numbers as a parameter and returns an array of percentages?

I'm currently a beginner and trying to understand how to basically use a function get an array of the numbers from each input to then figure out how to make an individual percentage for each candidate. In the JS, using that to get the total but is there a way to get each individual number from each input somehow? Maybe I'm going into a wrong direction with my for loop :/ Any direction or hints would be great.
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>
<output id="totalvotes"></output>
Here's the JS for it
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var totalVotes = 0;
for( var i = 0; i < votes.length; i ++ ) {
totalVotes += parseInt(votes[i].value);
}
document.getElementById("totalvotes").innerHTML = totalVotes;
}
Looks like you have a good grasp of getting the sum. To create an array, there's several ways you can do that but I recommend mapping it from the collection of elements like this:
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var total = document.getElementById("totalvotes");
// create new array
var percentages = [];
var totalVotes = 0;
// reset innerHTML in case loop returns early due to invalid value
total.innerHTML = "";
// reset each vote percentage
for (var i = 0; i < votes.length; i++) {
votes[i].nextElementSibling.innerHTML = "";
}
// overwrite each index with value
for (var i = 0; i < votes.length; i++) {
totalVotes += percentages[i] = parseInt(votes[i].value);
// one of the values is invalid
if (isNaN(percentages[i])) return;
}
total.innerHTML = totalVotes;
// calculate percentages here by mapping array of votes
for (var i = 0; i < percentages.length; i++) {
percentages[i] = 100 * percentages[i] / totalVotes;
votes[i].nextElementSibling.innerHTML = percentages[i].toFixed(2) + "%";
}
}
document.addEventListener('change', totalVotes)
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
<output></output>
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
<output></output>
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
<output></output>
</div>
<output id="totalvotes"></output>
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var totalVotes = 0;
var percentages = [];
for( var i = 0; i < votes.length; i ++ ) {
totalVotes += parseInt(votes[i].value);
percentages[i] = parseInt(votes[i].value);
}
percentages = percentages.map(function(candidateVotes) {return candidateVotes/totalVotes;});
document.getElementById("totalvotes").innerHTML = totalVotes;
}
The percentages are in the array of the same name, then you can do whatever you want with it!
Hopes this helps!
You mostly have the idea. You just need to attach some event handlers (with one other minor change).
function totalVotes() {
var votes = document.getElementsByName("votesPerPerson");
var totalVotes = 0;
for(var i = 0; i < votes.length; i++) {
totalVotes += parseInt(votes[i].value || 0); // "Minor change" here
}
document.getElementById("totalvotes").innerHTML = totalVotes;
}
// Additions below this point
var votes = document.getElementsByName("votesPerPerson");
for( var i = 0; i < votes.length; i ++ ) {
votes[i].addEventListener('change', totalVotes);
}
totalVotes(); // Run once to get 0 to show without changing anything
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>
<output id="totalvotes"></output>
Now, that code works, but note some of the repetition, global variables, etc. Here's an alternative that may offer you some different ways of accomplishing the same things:
// If you want to know what this outer function is, look up "IIFE"
(function() {
'use strict';
// Get the elements (and make sure they are put in an array)
var voteInputEls = Array.from(
document.getElementsByName('votesPerPerson')
);
// This is used below to handle the change event
function setTotalVotes() {
// "reduce" the voteInputEls array to a total value
var totalVotes = voteInputEls.reduce(function (lastVal, voteInputEl) {
return lastVal + parseInt(voteInputEl.value || 0);
}, 0);
document.getElementById('totalvotes').innerHTML = totalVotes;
}
// Attach event listeners
voteInputEls.forEach(function(voteInputEl) {
voteInputEl.addEventListener('change', setTotalVotes);
});
setTotalVotes(); // Run once to get 0
})();
<div>
<label for="votes1">Votes for Candidate 1</label>
<input type="number" name="votesPerPerson" id="cand1" placeholder="Vote count">
</div>
<div>
<label for="votes2">Votes for Candidate 2</label>
<input type="number" name="votesPerPerson" id="cand2" placeholder="Vote count">
</div>
<div>
<label for="votes3">Votes for Candidate 3</label>
<input type="number" name="votesPerPerson" id="cand3" placeholder="Vote count">
</div>
<output id="totalvotes"></output>

Limit the number of check-boxes allowed to be checked

function CountChecks(whichlist,forarray,maxchecked,latestcheck) {
// An array containing the id of each checkbox to monitor.
// List the id of each checkbox in the set. If more than
// one set, list other sets in their own arrays. The
// array name to use is passed to this function.
*// THIS PART IMPORTANT*//
var listone = new Array("1", "2", "3", "4", "5", "6");
*// THIS PART IMPORTANT*//
// End of customization.
var iterationlist;
eval("iterationlist="+whichlist);
var count = 0;
for( var i=0; i<iterationlist.length; i++ ) {
if( document.getElementById(iterationlist[i]).checked == true) { count++; }
if( count > maxchecked ) { latestcheck.checked = false; }
}
if( count > maxchecked ) {
alert('Sorry, only ' + maxchecked + ' may be checked.');
}
}
This is you can see CHECKBOX CHECK LIMITER.. And you can see works with function. I wanna do send this to js file from the page.. but Its not very functional becouse of array part. It has to create array's own by own.. I add the variable function part 'forarray'.. I dont know javascript and Im asking you it has to be like this when it create own arrays.
var {whichlist variable} = new Array({forarray variable list});
And HTML code like this.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','1',3,this)" value="2x2">2x2
<input id='2' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','2',3,this)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','3',3,this)" value="2x3">2x3
<input id='4' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','4',3,this)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','5',3,this)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','6',3,this)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','7',2,this)" value="red">Red
<input id='8' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','8',2,this)" value="gold">Gold
<input id='9' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','9',2,this)" value="green">Green
<input id='10' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','10',2,this)" value="silver">Silver
<input id='11' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','11',2,this)" value="blue">Blue
</p>
You do not need to do all of that. All you need to do is pass a reference to the element into the function and then use its name to query a list of its siblings. Count the number of checked boxes and prevent any others from being checked.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="listone" onclick="javascript:checkNumChecked(this, 3)"
value="2x2">2x2
<input id='2' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x3">2x3
<input id='4' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="red">Red
<input id='8' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="gold">Gold
<input id='9' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="green">Green
<input id='10' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="silver">Silver
<input id='11' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="blue">Blue
</p>
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
if (checked > limit) {
siblings[ct].checked = false
alert('Sorry, only ' + limit + ' item(s) may be checked.');
break;
}
}
}
</script>
However, alerts are annoying to end users. A much better way of doing this is to disable the other check boxes once the limit has been reached and re-enable them when a box is unchecked.
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>
To have the same, but make it work using only ids you can do the following:
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = [], checked = 0, item_num = parseInt(ele.id),
sct = (item_num < 7) ? 1 : 7, ect = (item_num < 7) ? 6 : 11;
for (ct = sct; ct <= ect; ct++) {
siblings.push(document.getElementById(ct));
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>

Javascript taking .innerHTML on indexOf checked

I have a variable named 'options'. Whenever a user checks one of the checkboxes, I need 'options' to populate the string with the .innerHTML for each checked checkbox. For example, when Instagram and Google+ are checked, 'options' would = Instagram, Google+.
html:
<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>
javascript:
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;
}
}
}
JSFiddle: http://jsfiddle.net/rynslmns/LQpHQ/
I would recommend tabulating the information each time they change a check state. What you're doing now is problematic; currently you start at 0, but end up being in the negative (total price) quickly by checking and unchecking a couple of options.
Also, options, as a string, will become difficult to keep up with. I'd probbaly make that an array that you can add/remove from (but if you tabulate at the end, there's no worrying).
For example:
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total'),
total2 = document.getElementById('payment-rebill');
// Perform the summing
// Though I'm not sure where total is coming from, but you can work that out.
// And for now I have it alerting the options, but you can do whatever you'd like with that.
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(', '));
}
// bind events to sum it on every change
for (var i = 0; i < inputs.length; i++){
inputs[i].addEventListener('change', sumItUp);
}
// Polyfill for trim()
if (!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
jsFiddle
You won't be able to use .innerHTML to get the text of the checkbox since it doesn't contain any text. You'll want to use .nextSibling instead. Something like this should work:
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 + ',';
}
}
}
Of course you'd also want to handle when a checkbox is unselected as well.

Categories