get the sum of two checkbox on check - javascript

hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>

var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>

You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>

Related

How to insert price based on checkbox checked

I have a form where I calculate the price based on the checkboxes checked. But I am having trouble as its not updating the final price correctly. I did some jQuery coding but it's not functioning properly. How can I debug the code and fix it?
//Price Calculator
$(document).ready(function(){
function Calculator(){
let totalAmount = 0;
if($('input[datasource=service_0]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 395;
return totalAmount;
}else if($('input[datasource=service_1]').is(':checked')){ // First Checkbox targeted using datasource attribute
totalAmount = 392;
return totalAmount;
}else if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2) {
totalAmount = 397;
return totalAmount;
}
}
//Insert Updated Amount to Budget field
$("input[type=checkbox]").on("click", function(){
if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2){
$("input[name=wpcf-book-amount]").val(Calculator());
} else{
$("input[name=wpcf-book-amount]").val(Calculator());
}
})
})
<div class="extra-services">
<ul>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="5" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_0">
<label for="wpcf-additional-services">Cot (EUR 5)</label>
</li>
<li>
<input type="checkbox" name="wpcf-additional-services[]" data-value="2" id="wpcf-fields-checkboxes-option-d41b805f6cbf1d0ab6ee12b8dda8b47d-1" datasource="service_1">
<label for="wpcf-additional-services">BABY CHAIR (EUR 2)</label>
</li>
</ul>
<input type="text" name="wpcf-booking-amount" id="booking_field" placeholder="Booking Amount (System Generated)" readonly>
</div>
Form containing the fields responsible to calculate the booking amount
<html>
<head></head>
<body>
<input type="checkbox" id="1st" onclick="ge()" value=500>
<label for="1st"> I have a bike</label><br>
<input type="checkbox" id="2nd" onclick ="ye()" value=200>
<label for="2nd"> I have a car</label>
<input type="number" id="here" value="0">
<script>
var amt = 0;
var st = document.getElementById("1st");
var nd = document.getElementById("2nd");
var num = document.getElementById("here");
function ge() {
if(st.checked == true ){
var g = parseInt(st.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(st.value);
num.value = amt;
}
}
function ye() {
if(nd.checked == true){
var g = parseInt(nd.value);
amt = amt + g;
num.value = amt ;
}
else{
amt = amt - parseInt(nd.value);
num.value = amt;
}
}
</script>
</body>
</html>
Here you go if it's only for two checkbox this will work, for live demo click here

Function triggers when checkbox is checked, but clears when unchecked

Here is a simple calculation that is run when a checkbox is checked:
function calculate() {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
//output
document.getElementById("drinkPrice").value = '$' +
parseFloat(drinkCost).toFixed(2);
};
Number of guests:
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>
How can the calculation be cleared (or hidden) when the check box is unchecked?
Thanks
You can use the checked property of checkbox to identify the checkbox is checked or unchecked. The demo with your Code as:
function calculate() {
if (document.getElementById("A").checked) {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
//output
document.getElementById("drinkPrice").value = '$' +
parseFloat(drinkCost).toFixed(2);
} else {
document.getElementById("drinkPrice").value = "";
}
};
Number of guests:
<input type="number" name="guests" id="guests" value="4">
<br>
Drinks:
<input type="checkbox" name="drinks" id="A" onchange="calculate()">
<output id="drinkPrice"></output><br>
I would highly suggest you do not use the onchange event, use the onclick instead, for compatibility reasons best explained by #T.J. Crowder on this question
Simply change the onchange="calculate(this)" inside the checkbox tag to:
<input type='checkbox' onclick='calculate(this);'>
Check the checkbox current state and reset the value if the state is false.
function calculate() {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
//output
document.getElementById("drinkPrice").value = '$' +
parseFloat(drinkCost).toFixed(2);
if(!document.getElementById('A').checked) {
document.getElementById("drinkPrice").value = ""
}
};
Number of guests:
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>
You have to check if the checkbox check value is true.
Try this.
function calculate() {
if (!document.getElementById("A").checked) {
document.getElementById("drinkPrice").value = "";
} else {
var guests = document.getElementById("guests").value;
var drinkRate = 2;
var drinkCost = drinkRate * guests;
document.getElementById("drinkPrice").value = '$' + parseFloat(drinkCost).toFixed(2);
}
};
Number of guests:
<input type="number" name="guests" id="guests" value="4"><br>
Drinks<input type="checkbox" name="drinks" id="A" onchange="calculate()"><output id="drinkPrice"></output><br>

Adding checkbox with multiple value

I have a set of books in checkboxes which a user can select. Every time a book is checked the price adds up. I also need to add its corresponding weight. I've modified this very useful example but to no avail.
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox"> Instagram
</label>
<label class="checkbox">
<input value="50" bweight=".4" type="checkbox" class="sum" data-toggle="checkbox"> Review site monitoring
</label>
<label class="checkbox">
<input value="30" bweight=".2" type="checkbox" class="sum" data-toggle="checkbox"> Google+
</label>
<label class="checkbox">
<input value="20" bweight=".6" type="checkbox" class="sum" data-toggle="checkbox"> LinkedIn
</label>
<div class="card-charge-info">
<span id="payment-total">0</span>
</div>
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
totwgt = document.getElementById('payment-w');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
var add = this.wgt * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
totwgt.innerHTML = parseFloat(total1.innerHTML) + add
}
}
Heres the code https://jsfiddle.net/u8bsjegk/2/
There's several issues in your code. Firstly you define the add variable in two places, one for the value the other for weight so your calculation is broken from there. Also note that bweight is not a valid attribute on the input element. To add your own meta data you should use a data-* attribute instead.
Try this:
var inputs = document.getElementsByClassName('sum'),
totalValue = document.getElementById('payment-total'),
totalWeight = document.getElementById('payment-w');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var value = parseFloat(this.value);
var weight = parseFloat(this.dataset.weight);
totalValue.innerHTML = parseFloat(totalValue.innerHTML) + value
totalWeight.innerHTML = parseFloat(totalWeight.innerHTML) + weight
}
}
As you've tagged this question with jQuery, here's a working implementation for that
var $inputs = $('.sum'),
$totalValue = $('#payment-total'),
$totalWeight = $('#payment-w');
$inputs.change(function() {
var value = parseFloat(this.value);
var weight = parseFloat($(this).data('weight'));
$totalValue.text(function(i, text) {
return parseFloat(text) + value;
});
$totalWeight.text(function(i, text) {
return parseFloat(text) + weight;
});
})
Working example
You have few issues:
You redeclare add variable
you have typo in total1 it should be totwgt
you don't have element with payment-w id
instead of this.wgt you should use this.getAttribute('bweight')
https://jsfiddle.net/u8bsjegk/6/

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

Javascript checkbox values

I have this javascript code, that substracts from a total sum, a value when a checkbox is checked. In my case for each checkbox checked it substracts 20.
<script language="JavaScript">
function Calculate(){
var tag = window.document.getElementsByClassName("hsnb"), total = <? echo $total; ?>;
for (var i in tag){
total -= tag[i].checked && !isNaN(Number(20)) ? Number(20) : 0;
}
var cucu = + total.toFixed(2);
if(cucu < "20"){
alert("You dont have enough points!");
for(i = 1; document.getElementById("bifa" + i) !== null; i++) {
if (document.getElementById("bifa" + i).checked){
} else {
document.getElementById("bifa" + i).disabled = true;
}
}
}
window.document.getElementById("outputDiv").innerHTML = '<span style="font-size:20px;">You have: POINTS' + cucu + '</span>';
}​
</script>
I want to give each checkbox a certain value, let's say:
<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">
And if i check the first checkbox it should substract 10 and if i check the second checkbox substract 20. You know what i mean, substract the value for each checkbox. Can you help me with this?
Hi you should try using jQuery, something like
var sub = 0;
jQuery("input[name=check]:checked").each(function(index, element){
sub = sub + jQuery(element).val();
});
var total = yourNumber - sub;
I'haven't tested this snippet but it should work
Hope it helps
In plain javascript you can attach an event to each input an check the "checked" property each time the handler is invoked; if true then substract the input value from the total sum:
<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">
<script type="text/javascript">
window.onload = function(){
var aBox = document.getElementsByTagName("input"), iTotal = <? echo $total; ?>;
Array.prototype.forEach.call(aBox,function(oCheck, iIdx,aBox){
oCheck.onclick = function(){
if(this.checked){
iTotal = iTotal - this.value;
console.log(iTotal);
}
}
});
}
</script>

Categories

Resources