Javascript - Calculating Sum of Checkboxes From Array - javascript

Based on the answers below I have edited the post to give some more details. Thanks everyone.
EDITED:
This is the code I have:
#foreach($amount_data as $amount)
<div class="col-sm-12">
<div class="input-checkbox">
<div class="inner"></div>
<input type="checkbox" name="items[]" value="{{$amount->amount}}" onchange="checkTotal()" />
</div>
<span>{{$amount->item_name}} - <b>{{$amount->amount}} {{$form->currency}}</b></span>
</div>
#endforeach
<br/> Total: <input type="text" size="2" name="total" value="0" />
#endif
Javascript:
<script type="text/javascript">
function checkTotal() {
var sum = 0,
frm = document.getElementById("payment-form"),
cbs = frm["items[]"],
i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
sum += parseInt(cbs[i].value);
}
}
frm.total.value = sum;
}
</script>
Form info:
<form action="{{url('secure-checkout/'.$form->unique_url_code)}}" method="POST" id="payment-form" name="payment-form">
Doesn't seem to work. No errors in console. Anything wrong?

You would need to use bracket notation because of the [] in the name
document.listForm["items[]"][i].checked
function checkTotal() {
var sum = 0,
frm = document.getElementById("payment-form"),
cbs = frm["items[]"],
i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
sum += parseInt(cbs[i].value);
}
}
frm.total.value = sum;
}
<form name="payment-form" id="payment-form">
<input type="checkbox" name="items[]" value="2" onchange="checkTotal()" />2<br/>
<input type="checkbox" name="items[]" value="5" onchange="checkTotal()" />5<br/>
<input type="checkbox" name="items[]" value="10" onchange="checkTotal()" />10<br/>
<input type="checkbox" name="items[]" value="20" onchange="checkTotal()" />20<br/>
Total: <input type="text" size="2" name="total" value="0" />
</form>

Here is an answer using jQuery. Hope this helps a bit! I've separated the listener and the function as I believe it makes things easier to edit later on. You could combine them to shorten the code.
//Listener for the checkbox
$("input[name='choice']").change(function() {
sumUp();
});
//Funtion that adds the total up
function sumUp() {
var sum = 0;
$(" input[name='choice']:checked").each(function() {
sum += parseInt($(this).val());
});
$("input[name=total]").val(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="listForm">
<input type="checkbox" name="choice" value="2" />2
<br/>
<input type="checkbox" name="choice" value="5" />5
<br/>
<input type="checkbox" name="choice" value="10" />10
<br/>
<input type="checkbox" name="choice" value="20" />20
<br/> Total:
<input type="text" size="2" name="total" value="0" />
</form>

You can get the Sum of checked checkboxes array by simply using Array.prototype.reduce():
function checkTotal() {
document.listForm.total.value = Array.prototype.reduce.call(
document.listForm.choice,
function (sum, el) {
return el.checked ? sum + +el.value : sum;
}, 0
);
}
<form name="listForm">
<input type="checkbox" name="choice" value="2" onchange="checkTotal()"/>2<br/>
<input type="checkbox" name="choice" value="5" onchange="checkTotal()"/>5<br/>
<input type="checkbox" name="choice" value="10" onchange="checkTotal()"/>10<br/>
<input type="checkbox" name="choice" value="20" onchange="checkTotal()"/>20<br/>
Total: <input type="text" size="2" name="total" value="0"/>
</form>

Related

decrease progress bar on radio input value click

I have 2 separate code in one audit.php file and trying to combine it to decrease progress bar by the value of click on radio input I just can't put the logic together The calculation should be (var total/$auditno * 100/100)
Variable
$auditno = "20";
Function for decrease progress bar, this is where calculation (var total/$auditno * 100/100) should replace value=v1-10
function decrease() {
var v1=document.getElementById('p1').value;
document.getElementById("p1").value= v1 - 10;
}
Function to calculate value of click radio input
function setRadios() {
function sumRadios() {
var total = 0, i = 1, oForm = this.form;
while (radgrp = oForm.elements['Set' + (i++)])
{
j = radgrp.length;
do
if (radgrp[--j].checked)
{
total += Number(radgrp[j].value);
break;
}
while (j);
}
oForm.elements.total.value = total.toFixed(2);
}
var i = 0, input, inputs = document.getElementById('myemailform').getElementsByTagName('input');
while (input = inputs.item(i++))
if (input.name.match(/^Set\d+$/))
input.onclick = sumRadios;
}
onload = setRadios;
and Html
<div id="wrapper">
<form id="myemailform">
<fieldset class="audit">
<legend>Set 1</legend>
<input id="r1" type="radio" name="Set1" value="0" /><label for="r1">0</label><br />
<input id="r2" type="radio" name="Set1" value="1" /><label for="r2">1</label><br />
<input id="r3" type="radio" name="Set1" value="2" /><label for="r3">2</label>
</fieldset>
<fieldset class="audit">
<legend>Set 2</legend>
<input id="r4" type="radio" name="Set2" value="0" /><label for="r4">0</label><br />
<input id="r5" type="radio" name="Set2" value="1" /><label for="r5">1</label><br />
<input id="r6" type="radio" name="Set2" value="2" /><label for="r6">2</label>
</fieldset>
<fieldset class="audit">
<legend>Set 3</legend>
<input id="r7" type="radio" name="Set3" value="0" /><label for="r7">0</label><br />
<input id="r8" type="radio" name="Set3" value="1" /><label for="r8">1</label><br />
<input id="r9" type="radio" name="Set3" value="2" /><label for="r9">2</label>
</fieldset>
<fieldset style="position:relative;top:36px;width:140px;">
<input id="total" type="text" name="total" value="" /><strong> total</strong>
<input type="reset" style="font-size:11px;" />
</fieldset>
</form>
</div><br><br>
<progress value="100" max="100" id=p1>100%</progress>
<input type=button value='Decrease' onClick='decrease();'>

JQuery - sum check boxes values according parent class

I have script that sum all checked checkboxs, but I would like to sum only checkboxs values where parent div has class="show_list_item"
$('input:checkbox').change(function (){
var total_srvs_amount = 0;
$('input[name="amount"]:checkbox:checked').each(function(){
total_srvs_amount += isNaN($(this).val()) ? 0 : parseInt ($(this).val());
console.log(total_srvs_amount);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show_list_item">
<input type="checkbox" name="amount" value="100">
<input type="checkbox" name="amount" value="120">
</div>
<div class="hide_list_item">
<input type="checkbox" name="amount" value="85">
<input type="checkbox" name="amount" value="90">
</div>
You can change the selector to apply the function on checkboxes inside .show_list_item:
$('.show_list_item input:checkbox').change(function ()
{
var total_srvs_amount = 0;
$('.show_list_item input[name="amount"]:checkbox:checked').each(function(){
total_srvs_amount += isNaN($(this).val()) ? 0 : parseInt ($(this).val());
console.log(total_srvs_amount);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show_list_item">
<input type="checkbox" name="amount" value="100">
<input type="checkbox" name="amount" value="120">
</div>
<div class="hide_list_item">
<input type="checkbox" name="amount" value="85">
<input type="checkbox" name="amount" value="90">
</div>

Drop down menu with HTML / JavaScript price calculation form

I'm trying to get a drop down menu to work with a price calculation form, but the drop down menu won't add any price value to the total price. I'm pretty bad at doing these things, so maybe one of you knows how to fix this?
This is the link to the code.
HTML:
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Extra domein $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Verlengservice $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Domein support $1.99
</label>
<select name="product" id="p3" onclick="totalIt()"/>
<option value="249">Thema 'Ambachtelijk'</option>
<option value="249">Thema 'Blog - Lifestyle'</option>
<option value="199">Thema 'Bed en Brood'</option>
<option value="249">Thema 'Freelancer'</option>
</select>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
JavaScript:
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
Any ideas?
You need to get the selected value from <select>
And Change onclick to onchange
The onchange event occurs when the value of an element has been changed.
Try this:
if(input[i].tagName == 'SELECT'){
total += Number(input[i].options[input[i].selectedIndex].value);
}
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if(input[i].tagName == 'SELECT'){
total += Number(input[i].options[input[i].selectedIndex].value);
}
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onchange="totalIt()"/>
Extra domein $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onchange="totalIt()"/>
Verlengservice $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onchange="totalIt()"/>
Domein support $1.99
</label>
<select name="product" id="p3" onchange="totalIt()"/>
<option value="249">Thema 'Ambachtelijk'</option>
<option value="249">Thema 'Blog - Lifestyle'</option>
<option value="199">Thema 'Bed en Brood'</option>
<option value="249">Thema 'Freelancer'</option>
</select>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
You should use onchange instead of onclick for select event. The main problem is that you aren't adding the value of select in the totalIt func. Might be a good idea to give the select a different id from your 3rd checkbox.
You need to modify your html, you are using same id like p3. Also, you need to handle onchange event. Please see the reference code:
var dropdownTotal = 0;
function dropDownTotalHandler() {
var x = document.getElementById("dropdownProducts").value;
dropdownTotal += parseFloat(x);
document.getElementById("total").value = "$" + dropdownTotal.toFixed(2);
}
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()" />
Extra domein $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()" />
Verlengservice $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()" />
Domein support $1.99
</label>
<select name="product" id="dropdownProducts" onchange="dropDownTotalHandler()" />
<option value="249">Thema 'Ambachtelijk'</option>
<option value="249">Thema 'Blog - Lifestyle'</option>
<option value="199">Thema 'Bed en Brood'</option>
<option value="249">Thema 'Freelancer'</option>
</select>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total" />
</label>
</fieldset>
<input value="Submit" type="submit" />
<input value="Reset" type="reset" />
</form>
If you want to keep the event handler same, then here is one of the way how you can do it. Hopefully, this is what you want but if not feel free to change it.
First, change the html to mention totalIt as event handler like below:
onchange="totalIt(this.value)"
Then modify the script code. Here, the addition into total is happening for one checkbox at a time:
<script>
var total = 0;
function totalIt(dropDownValue) {
if (!dropDownValue) {
total += parseFloat(event.target.value);
} else {
total += parseFloat(dropDownValue);
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
See if this is what you are looking for?

Calculate total on checkbox checked

HTML
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" /><label for="cat_1">cat_1</label><br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" /><label for="cat_2">cat_2</label><br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" /><label for="cat_3">cat_3</label><br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" /><label for="cat_4">cat_4</label><br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" /><label for="cat_5">cat_5</label><br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" /><label for="cat_6">cat_6</label><br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" /><label for="cat_7">cat_7</label><br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" /><label for="cat_8">cat_8</label><br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" /><label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Javascript
function calcAndShowTotal(){
var total = 0;
$('#catlist :checkbox[checked]').each(function(){
total =+ parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#pricelist :checkbox').click(function(){
calcAndShowTotal();
});
calcAndShowTotal();
I am getting particular value. WHY? I tried sum of total, i tried jquery but no success..
Use $('#catlist :checkbox:checked') selector to select checked check-boxes
[] is used as attribute selector and it could be used as '[type="checkbox"]' but it will not filter checked check-boxes
+ operator is not needed before parseFloat, it has to be total =+
Instead of calling handler, just invoke change handler using .change()
function calcAndShowTotal() {
var total = 0;
$('#catlist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Using Array#reduce
function calcAndShowTotal() {
var total = [].reduce.call($('#catlist :checkbox:checked'), function(a, b) {
return a + +$(b).attr('price') || 0;
}, 0);
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Instead of looping you can use change which will respond to and change event on the checkbox. Also you need add or subtract value like this += for addition on -= for subtraction
var _total = 0;
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')){
_total += parseFloat($(this).attr('price')) || 0;
}
else{
_total -= parseFloat($(this).attr('price')) || 0;
}
$('#total').val(_total);
})
JSFIDDLE
$('input:checkbox').change(function(){
var totalprice=0;
$('input:checkbox:checked').each(function(){
totalprice+= parseFloat($(this).attr('price'));
});
$('#total').val(totalprice)
});

How to sum value of radio button and checkbox in jquery

I have a code already working which calculates the sum of the radio buttons. I changed my mind in one of the radio button group and decided to make it a checkbox. When I tick items on the checkbox, the sum returns NaN. What would I add/change in my jquery in order for it to recognize the checkbox value?
Here's my code:
JQuery
< script type = "text/javascript" >
function calcscore() {
$(".calc:checked").each(function() {
score += parseInt($(this).val(), 10);
});
$('#price').text(score.toFixed(2));
$("input[name=sum]").val(score)
}
$().ready(function() {
$(".calc").change(function() {
calcscore()
});
});
< /script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="radio" name="rad1" id="rad1" />
</label>
<input type="hidden" name="rad1" value="100">
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" id="check1" value="200" />
</label>
<input type="hidden" name="check1" value="200">
</li>
<p>Total: PHP <span id="price">0</span>
</p>
Appreciate all the help.
This code code should answer your question:
function calcscore() {
score = 0;
$(".calc:checked").each(function () {
score += Number($(this).val());
});
$("#price").text(score.toFixed(2));
$("#sum").val(score)
}
$().ready(function () {
$(".calc").change(function () {
calcscore()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="radio" name="rad1" id="rad1" value="100" />
</label>
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" id="check1" value="200" />
</label>
</li>
<input type="hidden" name="sum" id="sum" value="0">
<p>Total: PHP <span id="price">0</span>
</p>
for your markup and usecase as it stands now in the question.try this
$('.calc').on('click', function() {
var sum = 0;
$('.calc:checked').each(function() {
sum += Number($(this).parent().next().val())
})
$('#price').text(sum)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="radio" name="rad1" id="rad1" />
</label>
<input type="hidden" name="rad1" value="100">
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" id="check1" value="200" />
</label>
<input type="hidden" name="check1" value="200">
</li>
<p>Total: PHP <span id="price">0</span>
</p>
try this,you dont need hidden fields for values.i removed them and used value property of checkbox.
$('.calc').on('click', function() {
var sum = 0;
$('.calc:checked').each(function() {
sum += Number($(this).val())
})
$('#price').text(sum)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<li>
<label>
<input class="calc" type="checkbox" name="check1" value="100" id="rad1" />
</label>
</li>
<li>
<label>
<input class="calc" type="checkbox" name="check1" value="200" id="check1" value="200" />
</label>
</li>
<p>Total: PHP <span id="price">0</span>
</p>

Categories

Resources