Add and subtract values with jQuery - javascript

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>

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

radioboxes only adds values on change, but doesn't subtract

I have 2 functions. One adds value from checkboxes and the other adds values from radioboxes to var tot.
The problem is that radiobox only adds value to var tot, but doesn't subtracts when unchecked.
I didn't have this problem until I scoped out the var tot, but it had to be done so that both functions could access it. Here is a code sample with the problem in action:
$(':checkbox:checked').prop('checked', false);
$('input[type="radio"]:checked').prop('checked', false);
$(document).ready(function() {
var tot = 0;
$('#usertotal').text('0 SEK')
$('input:checkbox').change(function() {
if (!$(this).is(':checked')) {
tot -= parseInt($(this).val());
} else {
tot += parseInt($(this).val());
}
$('#usertotal').text(tot + ' SEK')
});
$('input[type="radio"]').change(function() {
if ($(this).is(':checked')) {
tot += parseInt($(this).val());
} else if (!$(this).is(':checked')) {
tot -= parseInt($(this).val());
}
$('#usertotal').text(tot + ' SEK')
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<input type="radio" name="radioName" value="160 Yes">till 20
<input type="radio" name="radioName" class="someclass" value="5 Yes"> 20
<input type="checkbox" name="" value="29 Yes">BV
<div class="col-lg-4 col-mg-3 col-sm-12 col-xs-12 calculation-window">
Totalt: <span id="usertotal"></span>
</div>
jsfiddle: https://jsfiddle.net/ys1b9Lwv/12/
The issue seems to be that radio buttons don't fire the change event when they're unselected. Adding logging into the radio change event confirms this.
There are a few ways to solve this but I think the most elegant is to refactor the calculation of the total into a separate function, that checks the values of all the components involved in the sum / total.
I've come up with this solution:
var tot = 0;
$('#usertotal').text('0 SEK');
var update_tot = function () {
tot = 0; // reset
// sum of inputs that are checked
$('input:checkbox,input[type="radio"]').each(function(){
if ($(this).is(':checked'))
tot += parseInt($(this).val());
});
$('#usertotal').text(tot + ' SEK');
};
$('input:checkbox,input[type="radio"]').change(update_tot);
A cleaner rewrite of this could be:
var tot = 0;
$('#usertotal').text('0 SEK');
$('input:checkbox,input[type="radio"]').change(function () {
tot = 0; // reset
// sum of inputs that are checked
$('input:checkbox,input[type="radio"]')
.filter(':checked')
.each(function(){
tot += parseInt($(this).val());
});
$('#usertotal').text(tot + ' SEK');
});
We can't get de-select in radio box. so my solution is to fire deselect by ourself and identify already selected radio box. I am using class to achieve it.
$('input[type="radio"]').change(function() {
tot += parseInt($(this).val());
$(this).addClass("sel");
$('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect');
$('#usertotal').text(tot + ' SEK')
});
$('input[type="radio"]').bind('deselect', function(){
if($(this).hasClass("sel"))
{
$(this).removeClass("sel");
tot -= parseInt($(this).val());
$('#usertotal').text(tot + ' SEK')
}});

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

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;
}
});
});

Sum Checkboxes without POSTING values - Javascript

I've had a look around but could find a definitve answer.
Basically, I have a Total, with an ID that im trying to automatically update once a checkbox is clicked.
p style="font-size: 1.2em; font-weight: bold;"><b>Total Cost:</b> £<input value="0.00" readonly="readonly" type="text" id="total"/></p>
The checkbox will have a simple value such as 1.50 or similar. (these are dynamic) so
<input name="product" value="<?php echo $count*0.50 ?>" type="checkbox">
This may be very simple! But im not that hands on with Javascript
Handling both checking and unchecking a box to update the sum for the input with a working jsbin example, also assuming you are using jquery.
var sum = 0;
var total = $('#total');
var cbox = $('.cbox');
$('.cbox').on('change', function() {
if ($(this).prop('checked')) {
sum += parseFloat($(this).val());
updateTotal();
} else {
sum -= parseFloat($(this).val());
updateTotal();
}
});
function updateTotal() {
total.val(sum);
}
$('input[type=checkbox]').change(function() {
var sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
});
IF you just want the checked "product" check boxes:
$('input[type="checkbox"][name="product"]').on('change', function() {
var newtotal = 0;
$('input[type="checkbox"][name="product"]').filter(":checked").each(function() {
newtotal = newtotal + Number($(this).val());
});
$('#total').val(newtotal);
});
Sample fiddle to play around with: https://jsfiddle.net/ovqkcqvn/

Calculating totals when clicking checkboxes

I have a list of radio buttons represented by this code:
<form id="menu4strombolis">
input1 <input type="radio" name="menu1"><br />
input2 <input type="radio" name="menu2"><br />
input3 <input type="radio" name="menu3"><br />
input4 <input type="radio" name="menu4"><br />
input5 <input type="radio" name="menu5"><br />
input6 <input type="radio" name="menu6"><br />
input7 <input type="radio" name="menu7"><br />
</form>
Whenever a button is selected I need the subtotal and total to be updated.
This is how i want it to look.
Subtotal: <br />
Tax:<br />
Total:<br />
Where tax is always %7 or .7
The prices of menu 1 through 7 increments by $5. Menu1 is $5, menu2 is $10 and so forth.
I was trying to figure out the JavaScript to this but the problem is that i don't want it to display right after the buttons I want it displayed on the bottom of the page.
If I do document.write the whole page gets overwritten. Please help me on this issue guys. I am sure it's really simple.
Preamble
This sounds like homework to me. However, I find that the best way to learn, is by example.
So here's me, leading by example, OK?
You didn't give me much to go on, so for the sake of this example, I'm assuming you've got a list of checkboxes or radiobuttons that say Menu 1... Menu n. Each checkbox that is checked will be added to the subtotal, and then the tax calculated on top of that.
Doing it with radio buttons is a little easier, so I added that example as well.
On the bottom of the post are references for future study on what is used in this example.
If you have any further questions please ask them in the comment area at the bottom of this post.
The Javascript (checkboxes) | JSFiddle example (see it in action)
//Set the tax and base cost
var f_tax = 0.07,
i_menu_base = 5;
//Declare all the variables that will be used
var e_menu = document.getElementById("menu"),
e_checkboxes = e_menu.getElementsByTagName("input"),
e_subtotal = document.getElementById("sub_total");
// Add event listeners for when any checkbox changes value
for(var i = 0; i < e_checkboxes.length; i++){
e_checkboxes[i].onchange = function(){
//Recalculate subtotal
get_subtotal();
}
}
//get_subtotal calculates the subtotal based on which checkboxes are checked
function get_subtotal(){
var f_sub_total = 0.0,
f_grand_total = 0.0;
var subtotal, tax, grandtotal;
for(var i = 1; i <= e_checkboxes.length; i++){
//If the checkbox is checked, add it to the total
if(e_checkboxes[i-1].checked){
f_sub_total += i * i_menu_base;
}
}
//Calculate the grand total
f_grand_total = f_sub_total*(1+f_tax);
//Format them
subtotal = (Math.round(f_sub_total*100)/100).toFixed(2);
tax = (Math.round(f_tax*10000)/100).toFixed(2);
grandtotal = (Math.round(f_grand_total*100)/100).toFixed(2);
//Add them to the display element
e_subtotal.innerHTML = "Subtotal: "+subtotal+"<br />";
e_subtotal.innerHTML += "Tax: "+tax+"%<br />";
e_subtotal.innerHTML += "Total: "+grandtotal;
}
The Javascript (radio buttons) | JSFiddle example (see it in action)
//Set the tax
var f_tax = 0.07,
i_menu_base = 5;
//Declare all the variables that will be used
var e_menu = document.getElementById("menu"),
e_radios = e_menu.getElementsByTagName("input"),
e_subtotal = document.getElementById("sub_total");
// Add event listeners for when any checkbox changes value
for(var i = 0; i < e_radios.length; i++){
e_radios[i].onchange = function(){
//Recalculate subtotal
get_subtotal(this);
}
}
//get_index gets the index of the element (1..n)
function get_index(element){
for(var i = 1; i <= e_radios.length; i++){
if(e_radios[i-1] == element){
return i;
}
}
}
//get_subtotal calculates the subtotal based on the radio that was changed
function get_subtotal(el){
var f_sub_total = 0.0,
f_grand_total = 0.0;
var subtotal, tax, grandtotal;
f_sub_total += get_index(el) * i_menu_base
//Calculate the grand total
f_grand_total = f_sub_total*(1+f_tax);
//Format them
subtotal = (Math.round(f_sub_total*100)/100).toFixed(2);
tax = (Math.round(f_tax*10000)/100).toFixed(2);
grandtotal = (Math.round(f_grand_total*100)/100).toFixed(2);
//Add them to the element
e_subtotal.innerHTML = "Subtotal: "+subtotal+"<br />";
e_subtotal.innerHTML += "Tax: "+tax+"%<br />";
e_subtotal.innerHTML += "Total: "+grandtotal;
}
References for future study
In order in which they appear
getElementById()
getElementsByTagName()
looping through an array
onchange
Math.round(), decimal trick and toFixed()
innerHTML
Despite any additonal input from you, and my better judgement, I was bored so I did it all.
HTML:
<form id="menu4strombolis">input1
<input type="radio" name="menu1" value="5">
<br>input2
<input type="radio" name="menu2" value="10">
<br>input3
<input type="radio" name="menu3" value="15">
<br>input4
<input type="radio" name="menu4" value="20">
<br>input5
<input type="radio" name="menu5" value="25">
<br>input6
<input type="radio" name="menu6" value="30">
<br>input7
<input type="radio" name="menu7" value="35">
<br>
</form>
<button id="getTotal">Total</button>
<div id="subtotal">Sub-Total:</div>
<div id="tax">Tax:</div>
<div id="total">Total:</div>
JS:
var button = document.getElementById("getTotal");
button.onclick = function () {
var subtotalField = document.getElementById("subtotal");
var radios = document.forms["menu4strombolis"].getElementsByTagName("input");
var subtotal = 0;
var tax = 0;
var total = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
subtotal += parseInt(radios[i].value);
}
}
tax = (subtotal * .07).toFixed(2); ;
total = subtotal + tax;
document.getElementById("subtotal").innerHTML = "Sub-Total: $" + subtotal;
document.getElementById("tax").innerHTML = "Tax: $" + tax;
document.getElementById("total").innerHTML = "Total: $" + total;
};
and the working fiddle:
http://jsfiddle.net/RGvTt/1/
Though on a side note, you should either group some of the radios together in the same group... or make them checkboxs.
Updated to fix the bug that the OP couldn't fix:
http://jsfiddle.net/RGvTt/4/
Need to use parseFloat.
iPhone fiddle programming FTW!
What you want is element.innerHTML
So it would look something like this:
<form id="menu4strombolis">
input1 <input type="radio" name="menu1"><br />
input2 <input type="radio" name="menu2"><br />
input3 <input type="radio" name="menu3"><br />
input4 <input type="radio" name="menu4"><br />
input5 <input type="radio" name="menu5"><br />
input6 <input type="radio" name="menu6"><br />
input7 <input type="radio" name="menu7"><br />
</form>
..... ..html stuff here
Subtotal: <span id="subtotal"></span><br/>
Tax: <span id="tax"></span><br/>
Total: <span id="total"></span><br/>
ETC...
<script>
var subtotal = //whatever menu item is checked then .value();
var span_subtotal = document.getElementById("subtotal);
var tax = document.getElementById("tax");
var total = document.getElementById("total");
var the_tax = subtotal * .07;
span_subtotal.innerHTML = subtotal;
tax.innerHTML = the_tax;
total.innerHTML = subtotal + the_tax;
<script>

Categories

Resources