summing up in js with 2 options checked - javascript

i have this code in html
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>
and then the js
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
i need the first two checked checkboxes to sum up from start when page loads
and after the behavior of js to get me to 0 or to total of checkboxes when checking respectively unchecking

You could add an eventlistener to the page loading and just select the options using querySelectorAll("input[type=checkbox]") which selects all checkboxes, iterarate over them and sum them up.
var total = 0;
function calculate(option) {
if (option.checked) {
total += Number(option.value);
} else {
total -= Number(option.value);
}
document.getElementById("total").innerHTML = total;
}
window.addEventListener("load", function() {
var options = document.querySelectorAll("input[type=checkbox]");
for (var i = 0; i < options.length; i++) {
const o = options[i];
if (o.checked) total += Number(o.value);
}
document.getElementById("total").innerHTML = total;
}, false);
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>

Use a class:
<input type="checkbox" value="12" id="logo" class='summary' checked>
<input type="checkbox" value="19" id="bc" class='summary' checked>
<input type="checkbox" value="200" id="first" class='summary'>
<input type="checkbox" value="250" id="second" class='summary'>
document.addEventListener('DOMContentLoaded', function() {
var summerizers = document.querySelectorAll('.summary'),
counter = document.getElementById('counter');
for (var i = 0, c = summerizers.length; i < c; i++) {
summerizers[i].addEventListener('change', count);
}
count();
function count() {
var total = 0;
for (var i = 0, c = summerizers.length; i < c; i++) {
if (summerizers[i].checked) {
total += parseInt(summerizers[i].value, 10);
}
}
counter.value = total;
}
});
https://jsfiddle.net/r1khjrsd/

You can call the function, then recall the function onchange event. Don't need to pass this as parameter
function calculate() {
total = 0;
elements = document.getElementsByTagName('input');
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
total += Number(elements[i].value);
}
}
document.getElementById('total').innerHTML = total;
}
calculate();
<input type="checkbox" value="12" id="logo" checked onchange="calculate();">
<input type="checkbox" value="19" id="bc" checked onchange="calculate();">
<input type="checkbox" value="200" id="first" onchange="calculate();">
<input type="checkbox" value="250" id="second" onchange="calculate();">
<p id="total"></p>

To achieve expected result, use initial flag checking initial page load and checkTotal function to checked boxes on initial load
Steps:
Function checkedTotal to check all checked checkboxes and call calculate function with boolean value start
If start is true, only add checked checkbox values and restrict else part in calculate functionenter code here
code sample - https://codepen.io/nagasai/pen/XEyqEd?editors=1111
var total = 0;
function calculate(option,start) {
if (option.checked) {
total += Number(option.value);
} else {
if(!start){
total -= Number(option.value);
}
}
document.getElementById("total").innerHTML = total;
}
function checkedTotal(){
var checkList = document.getElementsByTagName('input');
for(var i =0; i < checkList.length; i++){
calculate(checkList[i], true)
}
}
checkedTotal()
<input type="checkbox" value="12" id="logo" checked onchange="calculate(this);">
<input type="checkbox" value="19" id="bc" checked onchange="calculate(this);">
<input type="checkbox" value="200" id="first" onchange="calculate(this);">
<input type="checkbox" value="250" id="second" onchange="calculate(this);">
<p id="total"></p>

Related

how to calculate the total of two incremented values from two different loops?

I have a function that calculates sum of input values. In this form I have checkboxes and number type inputs. I'm able to make this function work with either only checkboxes or textboxes but not both at the same time. The two input types enter in conflict. It's probably very trivial but I can't seem to figure it out. Any help?
js
$(document).on("change", ".calculate", function () {
calculateTotal();
});
function calculateTotal() {
//input type number
var textboxsum = 0;
//input type checkbox
var addonsum = 0;
//iterate through each input
$(".calculate").each(function () {
//get input type
var type = this.getAttribute("data-type");
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === "room") {
//add amount $35 per room
var amount = parseFloat(this.value * 35);
} else if (type === "addon") {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat(this.value * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() roundoff to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
there are few issues in the code, and you can use parseInt instead of parseFloat
$('.calculate').change(function() {
let amount = 0;
$(".calculate").each(function() {
const type = this.getAttribute('data-type');
if (!isNaN(this.value) && this.value.length !== 0) {
if (type === 'room') {
//add amount $35 per room
amount = parseInt(this.value, 10) * 35;
} else if (type === 'addon' && this.checked) {
amount += parseInt(this.value, 10) * 10;
}
}
});
$(".total_amount").html(amount.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount">0</span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
You have to declare var amount = 0; at top inside .each(). The reason you are getting NaN when type is not room then it will not execute code from if(type==='room') where you have declared amount and in end you have used textboxsum += parseFloat(amount);, so here amount will return undefined & textboxsum will become NaN.
Try it below.
$(document).on('change', '.calculate', function() {
calculateTotal();
});
function calculateTotal() {
//from input type number
var textboxsum = 0;
//from input type checkbox
var addonsum = 0;
//iterate through each textboxes and add the values
$(".calculate").each(function() {
//get input type
var type = this.getAttribute('data-type');
// declare amount variable here
var amount = 0; // <-- Change
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === 'room') {
//add amount $35 per room
// do not declare variable here. just use it
amount = parseFloat((this.value) * 35);
} else
if (type === 'addon') {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat((this.value) * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() method will roundoff the final sum to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">

How can I add input value in js array without cloning values?

I have simple js script that adds input values in array after clicking on input, it works as expected except that it duplicates values every time I'm clicking on another input, i.e. I click on input with value 5, array now is ["5"] then I click on input with value 4 and after that array is ["5", "5", "4"]. I've tried if statement with check on e.target but it didn't help. How can I add only input value on which I click, not all checked input values? Here is the link on pen. My HTML markdown:
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
And JS code:
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked == true) {
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
console.log(checkboxesChecked)
}
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
};
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
Any help and tips would be appreciated.
You need to reset the array each time and you should not just update it when checked.
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
checkboxesChecked.length = 0;
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
console.log(checkboxesChecked)
}
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
Personally I would use querySelectorAll
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
checkboxesChecked = Array.from(document.querySelectorAll("input:checked")).map(cb => cb.value)
p[0].innerHTML = checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
With your comments.... which still does not make sense with checkboxes, they should be buttons.
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked) checkboxesChecked.push(e.target.value)
p[0].innerHTML = checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>
You've said you want it to add the number that was clicked each time it's clicked to become checked, so if I click 5 (on) it's ["5"], then if I click it again (off) there's no change, and if I click it a third time we add "5" again for ["5", "5"]. If so:
function getCheckedCheckBoxes(e) {
if (e.target.checked) {
checkboxesChecked.push(e.target.value);
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
Live Example:
let checkboxes = document.getElementsByTagName('input');
let checkboxesChecked = [];
let p = document.getElementsByTagName('p');
function getCheckedCheckBoxes(e) {
if (e.target.checked) {
checkboxesChecked.push(e.target.value);
}
p[0].innerHTML = checkboxesChecked;
return checkboxesChecked;
}
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getCheckedCheckBoxes);
}
<div>
<input type="checkbox" value="5">
<input type="checkbox" value="4">
<input type="checkbox" value="3">
<input type="checkbox" value="2">
<input type="checkbox" value="1">
</div>
<p></p>

selecting multiple check boxes or radio buttons from different accordions and then displaying them

I want to make a custom cricket team and select multiple players from different teams and then displaying them
function getMultipleCheckbox(inputdata) {
var selectedItems = [];
var count = 0;
for (var i = 0; i < inputdata.length; i++) {
if (inputdata[i].checked) {
selectedItems[count] = inputdata[i].value;
count++;
}
}
for (var loop = 0; loop < selectedItems.length; loop++) {
console.log(selectedItems[loop]);
}
return selectedItems;
}
<p>Select players</p>
<form>
<input type="checkbox" name="owns" value="player1">player1<br/>
<input type="checkbox" name="owns" value="player2">player2<br/>
<input type="checkbox" name="owns" value="player3">player3<br/>
<input type="checkbox" name="owns" value="player4">player4<br/>
<input type="checkbox" name="owns" value="player5">player5<br/>
<input type="checkbox" name="owns" value="player6">player6<br/>
<input type="button" value="Get Values" onclick="getMultipleCheckbox(this.form.owns);" />
</form>

Push array of checkbox values to hidden field

I am running this code and it returns me set of values which are checked
var a = [];
var cboxes = $('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
//document.getElementByName('suppgrp[]').value = a[i];
}
I have a hidden field with ID suppgrp where I want to push all these values retrieved and wanted to pass it in array..
But I am not able to...where am I going wrong?
i have added some extra code which when page load then will call this function and also when change checkbox value then also call this function so all time it will work
loadCheck(); // initial call this function to load data
$('input[type="checkbox"]').change(function()
{
loadCheck();
});
function loadCheck() {
$('#hiddenValue').val('');
$('#showValue').val('');
var checkboxes = $('input[name="suppcheck[]"]:checked');
var data = [];
var len = checkboxes.length;
for (var i=0; i<len; i++) {
data[i] = checkboxes[i].value;
}
$('#hiddenValue').val(data);
$('#showValue').val(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="suppcheck[]" value="1" />
<input type="checkbox" name="suppcheck[]" value="2" />
<input type="checkbox" name="suppcheck[]" value="3" />
<input type="checkbox" name="suppcheck[]" value="4" />
<input type="checkbox" name="suppcheck[]" value="5" />
<input type="checkbox" name="suppcheck[]" value="6" />
<input type="checkbox" name="suppcheck[]" value="7" />
<input type="checkbox" name="suppcheck[]" value="8" />
<input type="checkbox" name="suppcheck[]" value="9" />
<input type="hidden" id="hiddenValue" />
<input type="text" id="showValue" />
</form>
var a = [];
jQuery('input[type="checkbox"]').change(function()
{
var cboxes = jQuery('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
var alval = '';
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
if (alval != '') {
alval += ','+a[i];
}else{
alval = a[i];
}
}
jQuery('#myhidden').val(alval);
});

Javascript looping through Page elements to change states?

This is relatively simple, but I'm missing something. I have 10 checkboxes on a page, in a table in a form. They all have names and id's of add0, add1, add2, etc. I wanted to build a "check/uncheck all" checkbox, but my code doesn't seem to be working. On firefox, using firebug, but it can't seem to follow the script execution.
function checkboxprocess(current)
{
for (i = 0; i < 10; i++)
{
if (current.checked)
{
document.getElementById("add" + i).checked = true;
}
else
{
document.getElementById("add" + i]).checked = false;
}
}
}
Checkbox:
echo "Select All: <input type=\"checkbox\" name=\"add\" id=\"add\" value=1 onChange=\"checkboxprocess(this)\"><br>";
You have extra ] in your code:
document.getElementById("add" + i]).checked = false;
And you don't have to check if is current checked each time in the loop, you can do it easily like this:
function checkboxprocess(current) {
for (i = 0; i < 10; i++) {
document.getElementById("add" + i).checked = current.checked;
// current.checked will return true/false
}
}
<form>
Select All: <input type="checkbox" onChange="checkboxprocess(this)">
<br /> <br />
<input type="checkbox" id="add0">
<input type="checkbox" id="add1">
<input type="checkbox" id="add2">
<input type="checkbox" id="add3">
<input type="checkbox" id="add4">
<input type="checkbox" id="add5">
<input type="checkbox" id="add6">
<input type="checkbox" id="add7">
<input type="checkbox" id="add8">
<input type="checkbox" id="add9">
</form>

Categories

Resources