How to insert price based on checkbox checked - javascript

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

Related

get the sum of two checkbox on check

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>

How to sum two results in Javascript

I am new at this and I got stuck.
I want to sum the two results that I get with this code.
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber">
<button onclick="myFunction()">Sum</button>
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
My question is - how to sum the two results and display it in 'Total:' at the end.
And how to remove the 'Sum' button, so you can see the result from the textbox in realtime in 'Total:' ?
Thanks in advance for any help :)
Edit : I need the sum from text box and the checkbox. For example : if the user have entered '5' this number equals 5 * 97 = 485. So '5' + Name(200) should be equals to 685.
Try this. I have defined a new method to calculate total amount. Whenever the checkbox or textbox is changed, the total is updated.
$(document).ready(function() {
document.getElementById("demo").innerHTML = 0;
$('label').click(function() {
$('.option:checked').each(function() {
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
updateTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
} else {
document.getElementById("demo").innerHTML = 0;
};
updateTotal();
}
function updateTotal(){
var total = 0;
var totalAmount = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
totalAmount = total + parseInt(document.getElementById("demo").innerHTML);
$('#total').html( totalAmount +' $');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber" onkeyup="myFunction()">
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
Create a new element with ID totalHolder and inside both functions call a third function (e.g. showTotal()) to sum those values:
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
showTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
showTotal();
}
function showTotal(){
var result1= parseInt($('#total').html());
var result2= parseInt($('#demo').html());
$("#totalHolder").html(result1+result2);
}
In order to remove onClick from button, you just need to set a listener:
$(docuemnt).ready(function(){
$("#myNumber").change(function(){
//Call your function inside the listener
myFunction()
})
})
Not sure if this satisfies your issue, but you need to do a couple things.
You should wrap input fields within a form.
Why are you mixing vanilla JS and jQuery? Stick with one or the other.
You should not be afraid to modularize your application with various functions.
Move the element queries out of the processing functions, instead pass their values in.
You can toggle the class in one loop, see below.
/* jQuery plugins */
(function($) {
/** Checks-off one or more checkboxes in a list of elements. */
$.fn.check = function(checked) {
return this.each(function(index, item) {
if (checked) {
$(item).prop('checked', 'checked');
} else {
$(item).removeProp('checked');
}
});
};
})(jQuery);
$(document).ready(function() {
$('#myNumber').val(5); // Set value to 5.
$('.option').slice(0, 1).check(true); // Check the first checkbox.
$('label').on('click', handleUpdate); // Attach a 'click' listener for label
handleUpdate(); // Call the function.
});
function handleUpdate() {
var sum = sumValues();
var num = $('#myNumber').val();
var mult = getMultiplier(num);
var total = num * mult + sum;
$('#total').html(total.toFixed(2) + ' $');
$('#demo').html(mult);
}
function sumValues() {
var total = 0;
$('.option').each(function() {
var isChecked = $(this).is(':checked');
if (isChecked) total += parseInt($(this).val());
$(this).parent().toggleClass('checked', isChecked);
});
return total;
}
function getMultiplier(value) {
if (value < 5) {
return value;
}
switch (value) {
case 5:
case 6:
case 7:
return 97;
case 8:
case 9:
case 10:
return 87;
default:
return 82;
}
}
label {
display: block;
}
.checked {
background : gold !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="check-form">
<input type="number" id="myNumber">
<button onclick="handleUpdate(); return false;">Sum</button>
<p id="demo"></p>
<label><input type="checkbox" class="option" value="200" /> Name</label>
<label><input type="checkbox" class="option" value="300" /> Blah</label>
<label><input type="checkbox" class="option" value="400" /> XYZ</label>
<label><input type="checkbox" class="option" value="800" /> Something</label>
<label><input type="checkbox" class="option" value="1200" /> Item</label>
</form>
<br>Total :
<div id="total">0 $</div>

Why is my JavaScript function not returning the checked array value?

In the following code, my alert() is returning 0 when it should be returning the checked box value. I need it to return the value in the designated array associated with the checkbox.
<!DOCTYPE html>
<html>
<head> <title> Program 4 Parallel Arrays </title>
<style type="text/css"></style>
<script type="text/javascript">
var priceArray = [45.25, 24.88, 32.35, 27.33,
34.85, 36.24, 85.33, 45.32];
var pageArray = [1098, 536, 500, 792, 912, 1224, 899, 504];
function funRun () {
var totalPages = 0;
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
alert("totalPages : " + totalPages);
}
function funRun1 () {
var subTotal = 0;
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
alert("subTotal : " + subTotal);
}
tax = (.06 * subTotal)
total= (subTotal + tax)
</script>
</head>
<body>
<form name="bookForm">
<input type="checkbox" name="books" value="Flanagan" />
JavaScript, the Definitive Guide: $45.25 <br>
<input type="checkbox" name="books" value="McFarland" />
JavaScript & JQuery: The Missing Manual: $24.88 <br>
<input type="checkbox" name="books" value="Morrison" />
Head First JavaScript: $32.35 <br>
<input type="checkbox" name="books" value="Wilton&McPeak" />
Beginning JavaScript: $27.33 <br>
<input type="checkbox" name="books" value="Quigley" />
JavaScript by Example: $34.85 <br>
<input type="checkbox" name="books" value="Goodman" />
JavaScript Bible: $36.24 <br>
<input type="checkbox" name="books" value="Gosselin" />
JavaScript: The Web Technologies Series: $85.33 <br>
<input type="checkbox" name="books" value="Suehring" />
JavaScript Step by Step: $45.32 <br>
<br>
<input type="button"
value="Calculate Total"
onclick="funRun();funRun1()"/>
<input type="reset"/>
<br>
<br>
<input type="text" name="totalPages"/>Total Pages<br>
<input type="text" name="subTotal"/>Subtotal<br>
<input type="text" name="tax"/>Tax<br>
<input type="text" name="total"/>Total</p>
</body>
</html>
The issue is at your for loop.
Use:
for(i=0; i<document.bookForm.books.length; i++) {
Instead of:
for(i=0; i<document.bookForm.books[i].length; i++) {
The reason is that you should not access the array element at the size definition.
Also, the following block is returning a ReferenceError since the subTotal variable was not defined out of the funRun1() function:
tax = (.06 * subTotal)
total= (subTotal + tax)
I would change your funRun() to this
function funRun () {
var inputs = document.forms[0].querySelectorAll('[name=books]');
var totalPages = 0;
for(i=0; i<inputs.length; i++) {
if(inputs[i].checked) {
totalPages = totalPages + pageArray[i];
}
}
alert("totalPages : " + totalPages);
}
Apply the same to funRun1() and you'll be fine.
Also, an error is raised in the console because of this
tax = (.06 * subTotal)
total= (subTotal + tax)
The reason is that your subTotal scope is only in funRun1()
I would even suggest putting your script just before the </body>
apart from the changes suggested by Zanon, take these two lines inside the function funrun1() -
tax = (.06 * subTotal)
total= (subTotal + tax)
Also, I would suggest you to call funrun1() from inside funrun() onclick event of the button.
The issue is that when you are indexing with i inside your for loop it is 0 at that time which means that your loop won't iterate at all. Therefore,
Change:
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
To:
for(i=0; i<document.bookForm.books.length; i++) {
if(document.bookForm.books[i].checked == true) {
totalPages = totalPages + pageArray[i];
}
}
and Change
for(i=0; i<document.bookForm.books[i].length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
To:
for(i=0; i<document.bookForm.books.length; i++) {
if(document.bookForm.books[i].checked == true) {
subTotal = subTotal + priceArray[i];
}
}
In addition, here is a working JS Fiddle for you.
https://jsfiddle.net/Kitchenfinks/5ovkdh2c/
Happy Coding!

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