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
I'm trying to create a sample accounting system, the checkbox can be add to the total after it's checked and the input text is the amount of the money.
but my result keep getting zero, I can't figure it out.
Anyone can help me handle this problem?
I've test that the length of total_ary is 0, I think that is the mainly problem
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount").value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You do
document.getElementsByName("amount").value
but getElementsByName returns a collection, not an element.
You do
var total_ary = [];
// ... code that doesn't reference total_ary
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
But since the code in between doesn't reference total_ary, the total ends up being 0.
From a selected checkbox, you need to navigate to the associated input:
document.getElementsByName("amount")[i].value
since i is the cb index you're iterating over, the same i in the amount collection will refer to the input you need.
Or, more elegantly, just navigate to the next element in the DOM when a checkbox is checked, and take the number for each product's price from the DOM too. You can also select only the checked checkboxes immediately with a :checked selector, and attach the event listener using addEventListener (instead of an inline handler; inline handlers should be avoided)
document.querySelector('button').addEventListener('click', () => {
let total = 0;
for (const input of document.querySelectorAll('[name=cb]:checked')) {
const price = input.nextSibling.textContent.match(/\d+/)[0];
const amount = input.nextElementSibling.value;
total += price * amount;
}
document.getElementById("result").innerHTML = total + "元";
});
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input><br>
<input type="checkbox" name="cb" checked>$20:<input><br>
<input type="checkbox" name="cb" checked>$30:<input><br>
</fieldset>
<button>Count</button>
<p>Total = <span id="result">
document.getElementsByName() returns a collection of elements. so calling value property will not work there as it does not have such property.
You can hold input elements with amount_inputs variable and iterate over it (in the example below by using spread syntax and Array.reduce())
And with Array.reduce() you can calculate the sum of the prices. There is no need for var amount = [] and var total_ary = [] variables.
Hope this helps
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount_inputs = document.getElementsByName("amount")
var total = 0;
var price = [10, 20, 30];
total = [...input_cb].reduce((total, cb, i) => {
if(cb.checked){
total += (parseInt(amount_inputs[i].value) || 0) * price[i]
// ^^^^^^^^^ This is to avoid NaN multiplication
}
return total
},0);
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Use Index while retrieving the element from document.getElementsByName("amount");
Use for loop on amount array not on total_ary
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount")[i].value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += isNaN(parseInt(total_ary[i])) ? 0 : parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You have made a few mistakes:
(1) If you want to keep all the checkboxes checked at initial stage
use checked="true" in place of checked
(2) getElementsByName("amount") returns an array, so you should use the index as well
(3) total_ary length is 0 initially.. therefore, you should run the loop with input_cb. (Here, you can do both the task with a single loop: refer code below)
Refer the code with corrections:
<!DOCTYPE html>
<html>
<head>Order sys
<script>
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked){
amount.push(parseInt(document.getElementsByName("amount")[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
total += parseInt(amount[i] * price[i]) //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
</script>
</head>
<body>
<fieldset>
<input type = "checkbox" name="cb" checked="true">$10:<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked="true">$20:<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked="true">$30:<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
</body>
</html>
You can refactor your code:
Fist use inputs of type number <input type="number" name="amount"> to accept only numbers from your end users
Then, you can work with indexed arrays like [...document.querySelectorAll('input[name="cb"]')] and loop only one time with Array.prototype.reduce() to get the total
Code example:
function Totalamount() {
const inputNumberArr = [...document.querySelectorAll('input[name="cb"]')]
const inputAmountArr = [...document.querySelectorAll('input[name="amount"]')]
const priceArr = [10, 20, 30]
const total = inputNumberArr.reduce((a, c, i) => {
const num = c.checked ? +inputAmountArr[i].value : 0
return a + num * priceArr[i]
}, 0)
document.getElementById('result').innerHTML = '$' + 0
document.getElementById('result').innerHTML = '$' + total
}
<fieldset>
<input type="checkbox" name="cb" checked> $10:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $20:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $30:
<input type="number" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Is this what you are looking for?
Errors that I identified.
Making use of document.getElementsByName("amount").value instead of making the respective amount field you were making use of the global selector.
Trying to loop total_ary array instead of amount array.
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amountInput = document.getElementsByName('amount');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked && amountInput[i].value){
amount.push(parseInt(amountInput[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type = "checkbox" name="cb" checked>$10
<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked>$20
<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked>$30
<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
i Have a function that I want to start only if another function is previously activated.
I have some CheckBoxes and I need to sum its values to get the total.
Only When a user has selected some of the CheckBoxes it must activate another checkbox with a discount.
I want that the discount checkbox get activated after the first selection because, if I don't do so, I could have a negative price.
Then (if it's possible) I want that the discount checkbox get deactivated is a user deselect all the previous CheckBoxes.
Is this possible?
Here's my script. I'm super new in JavaScript/jQuery so this might be a stupid question.
Thank you
$(document).on('change', getCheck);
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
//console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
//console.log(total);
//console.log(price_tot);
$('#rata').text(total +" €");
var finalprice = total;
//var Check = getCheck();
if(typeof(total) != "undefined" && total !== 0) {
$('[type="checkbox"]:checked').not(".sum").each(function(i, el) {
var Discount = parseFloat($(this).val());
finalprice = finalprice - Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
});
};
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="sum" type="checkbox" name="vehicle1" value="1000"> I have a bike<br>
<input class="sum" type="checkbox" name="vehicle2" value="2000"> I have a car<br>
<br><br><br>
<input id="discount" type="checkbox" name="discount" value="200"> Discount<br>
<div id="rata">rata</div>
Replace your js code with this code. the error will be resolved.
$( document ).ready(function() {
$("input[type='checkbox']").on('change', getCheck);
});
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
console.log(total);
//console.log(price_tot);
$('#rata').html(total +" €");
var finalprice = total;
var Check = function getCheck(){
if(typeof(Check) != "undefined" && Check !== null) {
$("#discount").toggle();
var Discount = parseFloat($(this).val());
finalprice -= Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
};
};
});
};
Trying to learn JQUERY/HTML, so I am making a shopping cart. I am trying to output subtotal, tax, shipping, and total cost to input boxes. The first 2, sub total and shipping cost show, but nothing is outputted for the last 2 input boxes.
HTML
<div class="form-group">
<div class="subTotal">
<label for="subtotal"><span>Sub Total</span><span>*</span><input type="number" class="input-field" name="subtotal" id="subtotal" disabled/></label>
<label for="shipping"><span>Shipping</span><span>*</span><input type="number" class="input-field" name="shipping" id="shipping" disabled/></label>
<label for="tax"><span>Tax</span><span>*</span><input type="number" class="input-field" name="tax" id="taxCost" disabled/></label>
<label for="total"><span>Total</span><span>*</span><input type="number" class="input-field" name="total" id="total" disabled/></label>
</div>
</div>
JS
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".cost").each(function () {
var value = $(this).text();
// add only if the value is number
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
var subtotal = sum;
var shippingCost = (sum * 0.085);
var tax = (((sum + shipping) * 0.11));
var total = (sum + shippingCost + tax);
$("#subtotal").val(subtotal);
$("#shipping").val(shippingCost);
$("#taxCost").val(tax);
$("#total").val(total);
};
Are you sure this isn't a typo?
var tax = (((sum + shipping) * 0.11));
Shouldn't it be
var tax = (((sum + shippingCost) * 0.11));
Alright so I tried to understand your code, first off I could not find .cost anywhere in the code so the output was 0 from the start, so I added a value to the inputs and then this.
This code block was your original code, the shipping variable is named wrongly, it's probably supposed to be shippingCost.
var tax = ((sum + shipping) * 0.11);
Here is the code.
https://jsfiddle.net/dbu41wpa/2/
Calculate total price after discount input OnChange not working
function CalcDiscount()
{
var qty = document.getElementById("ticket-count").innerText;
var value = document.getElementById("item-price").innerText;
var discount = document.getElementById("discount").value;
var total = value * qty;
var gtotal = total - discount;
//document.getElementById("total-price").value = gtotal;
$("#total-price").val(gtotal);
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Ticket Fare: <span id="item-price" class="item-price">450</span><br />
Ticket Number:<span class="ticket-count" id="ticket-count" > 5</span><br />
Discount: <input class="discount" id="discount" name="discount" type="text" onkeyup="CalcDiscount();"> <br /><br />
Total: <input class="total-price" id="total-price" name="totalprice" type="text" >
You need to convert your values from strings to numbers.
Try this:
function CalcDiscount()
{
var qty = parseInt(document.getElementById("ticket-count").innerText);
var value = parseInt(document.getElementById("item-price").innerText);
var discount = parseInt(document.getElementById("discount").value);
var total = value * qty;
var gtotal = total - discount;
//document.getElementById("total-price").value = gtotal;
$("#total-price").val(gtotal);
}