Limit number of clicks on radio button and multiply by a number - javascript

As you can see in the jsfiddle, when the #CreditCard radio button is clicked, the Total is multiplied by 1.02 and the Total is updated.
The problem is that the same button can be clicked multiple times and the number keeps multiplying.
I want to limit the number of times a button can be clicked to 1, but also want to be able to switch between Debit card and Credit card. (so when the other button is clicked, the limit is reset to 0?)
Any help is much appreciated.
https://jsfiddle.net/n52fy9am/2/
html
Total: <span id="totalPrice">£154.67</span>
<br>
<form>
<input id="DebitCard" type="radio" name="payment" checked>
<label for="DebitCard">Debit Card</label>
<br>
<input id="CreditCard" type="radio" name="payment">
<label for="CreditCard">Credit Card (2% extra)</label>
<br>
</form>
js
// credit card 2% surcharge
$('#CreditCard').on("click", function() {
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 1.02).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
});
// remove 2%
$('#DebitCard').on("click", function() {
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 0.98).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
});

Just use a flag to do it. Change the flag when radio button clicked. So that you can control whether to do the calculation or not.
Also, because you round it with toFixed(2), the decimal part of the number will be messed up when you do the calculation. So use a variable to store the initial value. Put it back when debitCard button is pressed.
var isCreditCard = false;
var initialPrice = 154.67;
$('#totalPrice').html("£" + initialPrice.toString());
// credit card 2% surcharge
$('#CreditCard').on("click", function() {
if (!isCreditCard) {
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 1.02).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
isCreditCard = true;
}
});
// remove 2%
$('#DebitCard').on("click", function() {
if (isCreditCard) {
// Update total
$('#totalPrice').html("£" + initialPrice.toString());
isCreditCard = false;
}
});

I took your JS fiddle and turned into a stack snippet ;)
I modified the code and placed comments wherever necessary.
I store initial count values that get incremented on every click, if that number exceeds 0 then the function gets cancelled, this remains true until the other radio is checked which resets the previously clicked one.
$(function() {
// keep count of n times clicked
var creditCardCount = 0;
var debitCardCount = 0;
// credit card 2% surcharge
$('#CreditCard').on("change", function() {
// if amount is greater or equal to 1 then abort the function
if (creditCardCount > 0) {
return false;
}
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 1.02).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
// increment credit card count
creditCardCount++;
// reset the other option to 0
debitCardCount = 0;
});
// remove 2%
// do the same here but for the opposite cards
$('#DebitCard').on("change", function() {
if (debitCardCount > 0) {
return false;
}
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 0.98).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
debitCardCount++;
creditCardCount = 0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Total: <span id="totalPrice">£154.67</span>
<br>
<form>
<input id="DebitCard" type="radio" name="payment" checked>
<label for="DebitCard">Debit Card</label>
<br>
<input id="CreditCard" type="radio" name="payment">
<label for="CreditCard">Credit Card (2% extra)</label>
<br>
</form>

I suggest you simplify your code. Check demo - Fiddle:
$(function() {
var lastRadioClicked = 'DebitCard',
canClick = true;
$('[name="payment"]').on("click", function() {
var surchargePercent;
if (lastRadioClicked === this.id) {
if (canClick) {
if (this.id === 'DebitCard') {
// debit
surchargePercent = 0.98;
} else {
// credit
surchargePercent = 1.02;
}
canClick = false;
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * surchargePercent).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
}
} else {
lastRadioClicked = this.id;
canClick = true;
}
});
});

Related

start a function if another function is active and activate some checkboxes only - JQuery

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 +" €");
};
};
});
};

How to calculate total?

I faced a problem for my code and I could not solve it. I have 2 functions, the first one calculates the total and second one discounts the total (if the user write the discount code, it will show the discounted total). But I don't know how to get and call the right value from total to keep it in the second function to calculate the discount because it always shows 0 in the amount. The TOTAL is for the first function and JavaScript code is for the second function.
total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;
function discount(coupon) {
var yCoupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var amount;
var input = document.getElementById('discount').value;
if (input == coupon) {
amount = price || 0 * 0.25;
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
Something like this?
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').value);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * (1 - .25) // 25% off coupon
document.getElementById("Offerprice").innerHTML = amount;
} else {
document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
}
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()"> discount</button>
<p><span id ="Offerprice"></span></p>
You have several issues in your code. Here is a working version. I hardcoded the total only for testing because I don't know the HTML for your tickets:
var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * 0.75; //discount of 25%
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>

jQuery calculating two values wrong and not sure why

Any ideas why the total I'm trying to calculate together is coming out as 1.00?
$(document).ready(function() {
// Hide initial values that need updating
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").hide();
// get current delivery rate
$("#get_rate").trigger('click');
// set a timeout and get total and shipping that was generated and add together for nnew total
setTimeout(function() {
// get cart sub-total
var a = $(".cart-total span").html().replace(/[$£]/gi, "");
var ib = $("#estimated-shipping em").html().replace(/[$£]/gi, "");
if (ib == "FREE") {
$("#estimated-shipping em").html("FREE");
var b = "0.00";
} else {
var b = parseFloat($("#estimated-shipping em").text().replace(/\$|£/gi, ""));
}
// add together sub-total and estimated shipping to new total
// update with new total with sub-total and added shipping
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
// show new values
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").show();
}, 2000);
$(".item-quantity input").on("change", function() {
document.location.href = location.href
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="cart-right">
<p class="cart-total">Sub-Total<span class="money">£1,245.00</span>
</p>
<p class="cart-vat">VAT 20% (included)<span class="money" style="display: block;">£249.00</span>
</p>
<p class="cart-delivery">Delivery (estimated)<span class="money" id="estimated-shipping">+ <em style="display: inline;">FREE</em></span>
</p>
<p class="cart-finalTotal">Total<span class="money" style="display: block;">£0.00</span>
</p>
</div>
In your subtotal, you have a comma, parseFloat will stop when it see a non numeric character that isn't a dot. So parse float is returning a 1 not a 1245. You need your regex to be something more on the lines of /[^0-9.]/g.
Here is code that is working:
$(document).ready(function() {
// Hide initial values that need updating
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").hide();
// get current delivery rate
$("#get_rate").trigger('click');
// set a timeout and get total and shipping that was generated and add together for nnew total
setTimeout(function() {
// get cart sub-total
var a = $(".cart-total span").html().replace(/[^0-9.]/gi, "");
if ($("#estimated-shipping em").text() == "FREE") {
$("#estimated-shipping em").html("FREE");
var b = "0.00";
} else {
var b = parseFloat($("#estimated-shipping em").text().replace(/[^0-9.]/gi, ""));
}
// add together sub-total and estimated shipping to new total
// update with new total with sub-total and added shipping
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
// show new values
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").show();
}, 2000);
$(".item-quantity input").on("change", function() {
document.location.href = location.href
});
});

JavaScript Calculating wrong

I am trying to perform calculation using JavaScript. When user enter less than 10 pages in input (#page) the cost is 1. if he adds more than 10, each page costs .10. there are 2 options for checkbox, if he clicks first checkbox 10 is added and second checkbox 15 is added.
This is working when it is done in sequential steps. (input then clicking checkbox).
Ex: Input is : 9 (total: 1)
click checkbox1 - duplicates (total : 11)
click checkbox1 - laser (total: 26)
Now if i change the Input to 11, then the total becomes 1.10 - even if both the checkboxes are checked.. (expected result should be - 26.10)
I am not sure how to do this...can anyone help me out
<html>
<head>
<title>Calculation</title>
<script>
function calculate() {
var pages=document.getElementById("page").value;
if(pages <=10) {
total.value=1;
}
if(pages >= 11) {
var extra_pages= pages - 10;
var new_total= extra_pages * .10;
var new_total1= 1 + new_total;
total.value= new_total1;
}
}
function checkbox1() {
if(document.getElementById("ckbox1").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 10;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox1").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 10;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
function checkbox2() {
if(document.getElementById("ckbox2").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 15;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox2").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 15;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
</script>
<body>
Enter a Number: <input type="text" id="page" value="1" oninput="calculate()">
<br>
<br><br><br><br>
duplicates <input type="checkbox" id="ckbox1" onclick="checkbox1()">
laser print: <input type="checkbox" id="ckbox2" onclick="checkbox2()"> <br><br>
Total: <input type="text" id="total">
</body>
</html>
You can use calculate for all changes instead of creating each one for each input, which makes the calculation complex.
// Get reference to inputs.
var page = document.getElementById("page");
var total = document.getElementById("total");
var dup = document.getElementById("ckbox1");
var laser = document.getElementById("ckbox2");
function calculate() {
// To Number
var pages = parseInt(page.value, 10);
var value = 0;
if (pages <= 10) {
value = 1;
} else {
var extra_pages = pages - 10;
var new_total = extra_pages * .10;
var new_total1 = 1 + new_total;
value = new_total1;
}
// Add 10 if dup is checked.
if (dup.checked) {
value += 10;
}
// Add 15 if laser is checked.
// These can be moved out like
// const laserVal = 15;
// value += laserVal if you don't want magic number here.
if (laser.checked) {
value += 15;
}
// Truncate float.
total.value = value.toFixed(1);
}
Enter a Number:
<input type="text" id="page" value="1" oninput="calculate()">
<br>
<br>
<br>
<br>
<br>
duplicates:<input type="checkbox" id="ckbox1" onclick="calculate()">
laser print:<input type="checkbox" id="ckbox2" onclick="calculate()">
<br>
<br>Total:
<input type="text" id="total">

Add and subtract values with jQuery

Need Help with following piece of jQuery code;
What I'm trying to do is;
add Amount into Total
when amount added Checkbox value get double
If checkbox state change, checkbox Updated value minus or add into Total accordingly
if Amount minus from Total, checkbox value change back to original
If checkbox state change, checkbox Updated value minus or add into Total accordingly
Following is the piece of jQuery Code
$('#Addcar').on('click', function() {
if($(this).html()=='Add') {
$(this).html('Remove');
var tot = parseFloat($('#TotalAmount').val()) + parseFloat($('#QuoteAmount').val());
var totcan = parseFloat($('#Cancelation').val()) + 2;
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
} else {
$(this).html('Add');
var tot = parseFloat($('#TotalPrice').val()) - parseFloat($('#QuoteAmount').val());
var totcan = parseFloat($('#Cancelation').val()) - 2;
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
}
});
$('#Cancelation').change(function(){
if($(this).is(':checked')){
total = parseFloat($('#TotalPrice').val()) + Number($(this).val());
} else {
total = parseFloat($('#TotalPrice').val()) - Number($(this).val());
}
$('#TotalPrice').val(total);
});
Here is the fiddle which explains better;
Updated Fiddle:
http://jsfiddle.net/55n8acus/7/
If QuoteAmount value added and checkbox value remove from Total and then remove QuoteAmount value , the result value will be wrong, it should be 52 not 48, the reason checkbox won't update and it still remove 4 from Total instead it should remove 2.
Thanks for all the help
Regards.
What I can understand from the question is that you want to subtract the value from total price, but you are accidentally using #TotalValue instead of #TotalPrice when you click on the checkbox, change the code to this, it will work as expected.
$('#Cancelation').change(function(){
if($(this).is(':checked')){
total = parseFloat($('#TotalPrice').val()) + Number($(this).val());
} else {
total = parseFloat($('#TotalPrice').val()) - Number($(this).val());
}
$('#TotalPrice').val(total);
});
here is the updated js fiddle :- jsfiddle.net/55n8acus/8
$('#Addcar').on('click', function() {
if($(this).html()=='Add') {
$(this).html('Remove');
var tot = parseFloat($('#TotalAmount').val()) + parseFloat($('#QuoteAmount').val());
var totcan = parseFloat($('#Cancelation').val()) + 2;
if(!$("#Cancelation").is(':checked')){
tot = tot -4;
}
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
$('#Cancel').html(totcan);
} else {
$(this).html('Add');
var tot = parseFloat($('#TotalPrice').val()) - parseFloat($('#QuoteAmount').val());
if(!$("#Cancelation").is(':checked')){
tot +=2;
}
var totcan = parseFloat($('#Cancelation').val()) - 2;
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
$('#Cancel').html(totcan);
}
});
$('#Cancelation').change(function(){
if($(this).is(':checked')){
total = parseFloat($('#TotalPrice').val()) + Number($(this).val());
} else {
total = parseFloat($('#TotalPrice').val()) - Number($(this).val());
}
$('#TotalPrice').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Add<br>
<input type="text" id="QuoteAmount" value="50" />
<input type="text" name="TotalAmount" id="TotalAmount" value="52" /><br>
<input type="text" name="TotalPrice" id="TotalPrice" value="0" /><br>
<input type="checkbox" id="Cancelation" value="2" checked> <span id="Cancel">2</span>

Categories

Resources