Javascript: how to calculate the total [duplicate] - javascript

This question already has answers here:
Variable keeps getting reset to its original value
(2 answers)
Closed 4 years ago.
I have a problem with the total price of a cart. Theoretically, the function should update the total whenever I press the "buy" button, but it just replaces the price.
Instead of doing 0 + price + price + price +..., it does 0 + price, then again 0 + price.
How can I fix it?
function buy(id) {
var total = 0;
for (var i in albums) {
if (albums[i].id == id) {
if (albums[i].quantity > 0) {
albums[i].quantity--;
total += albums[i].price;
}
}
}
for (var i in singles) {
if (singles[i].id == id) {
if (singles[i].quantity > 0) {
singles[i].quantity--;
total += singles[i].price;
}
}
}
for (var i in soundtracks) {
if (soundtracks[i].id == id) {
if (soundtracks[i].quantity > 0) {
soundtracks[i].quantity--;
total += soundtracks[i].price;
}
}
}
document.getElementById('purchases').innerHTML = total;
}
<button onClick='buy("+this.id+")'>Buy</button>

Everytime time you do a button click, you are calling yourbuy function. In that function you are declaring var total = 0. Thats why it always starts with 0. You should declare your total not with 0 but with previous number. In your case, that would be from document.getElementById('purchases').innerHTML. So
total = document.getElementById('purchases').innerHTML, or move var total = 0 outside of function.

I moved the total out as others pointed out, but I also made some refactors to remove repeated logic.
//moved the total outside of the method so it is not reinitialized
//as others have already mentioned
var total = 0;
//also reduced your repeated logic
function totalElements (elements, id) {
elements.forEach(function(element){
if (element.id == id && element.quantity > 0) {
element.quantity--;
total += element.price;
}
});
}
function buy(id) {
totalElements(albums, id);
totalElements(singles, id);
totalElements(soundtracks, id);
document.getElementById('purchases').innerHTML = total;
}
<button onClick='buy("+this.id+")'>Buy</button>

Related

JS random order showing divs delay issue

I got function within JS which is supposed to show random order divs on btn click.
However once the btn is clicked user got to wait for initial 10 seconds ( which is set by: setInterval(showQuotes, 10000) ) for divs to start showing in random order which is not ideal for me.
JS:
var todo = null;
var div_number;
var used_numbers;
function showrandomdivsevery10seconds() {
div_number = 1;
used_numbers = new Array();
if (todo == null) {
todo = setInterval(showQuotes, 10000);
$('#stop-showing-divs').css("display", "block");
}
}
function showQuotes() {
used_numbers.splice(0, used_numbers.length);
$('.container').hide();
for (var inc = 0; inc < div_number; inc++) {
var random = get_random_number();
$('.container:eq(' + random + ')').show();
}
$('.container').delay(9500).fadeOut(2000);
}
function get_random_number() {
var number = randomFromTo(0, 100);
if ($.inArray(number, used_numbers) != -1) {
return get_random_number();
} else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
Question: How to alter the code so upon the btn click divs will start showing right away without initial waiting for 10 seconds? (take in mind I want to keep any further delay of 10 seconds in between of each div being shown)
Thank you.
Call it when you begin the interval
todo = setInterval((showQuotes(),showQuotes), 10000);

Update price on change inlcuding on select

This is my fiddle:
https://jsfiddle.net/btekbtek/6gxztk4f/6/
When I type qty, I automatically calculate price.
I want also include select option that is adding
£1 per 1 qty.
If someone type 10 qty - price should be qty10*(£1*10)*price
Currently when I add:
// update price if option change
var optionprice = 0;
var getPriceOption = function() {
jQuery("#select_21").change(function() {
if (jQuery(this).val() === '63') {
optionprice = 0;
} else {
optionprice = 1;
}
}); //end update optionprice
return optionprice;
}; //end get PriceOption
console.log(getPriceOption);
getPriceOption is undefined. I was trying to add it after before and same result.
I cannot change anything in HTML, just in jQuery.
This was enough:
var updateprice = $("#select_21 option:selected").attr('price');
added in :
while (i--) {
if (qty >= tierPrices[i]['price_qty']) {
var updateprice = $("#select_21 option:selected").attr('price');
var calc_price = tierPrices[i]['price'] * qty + (updateprice*qty);
return (calc_price).toFixed(2)
}
}

on click remove field,amount get reduced but it shows -ve sign

Function to remove fields and substract amount from total:
function removeHtmlRow(nxt){
$("#FD"+nxt).remove();
var totAmtR = 0;
$('input.price').each(function (index, cvalue) {
if(cvalue.value != '' && cvalue.value > 0){
totAmtR -= parseFloat(cvalue.value);
}
});
alert(totAmtR);
$("#totalAmount").val(parseFloat(totAmtR));
}
Function to calculate total:
function calTotalAmount(){
var totAmt = 0;
$('input.price').each(function (index, cvalue) {
if(cvalue.value != '' && cvalue.value > 0){
totAmt += parseFloat(cvalue.value);
}
});
$("#totalAmount").val(parseFloat(totAmt));
}
</script>
screenshot shows: after remove field total show remaining amount with -ve
In your removeHtmlRow function you are subtracting everything from 0, so it will be negative. Just recalculate the amount using your existing calTotalAmount function:
function removeHtmlRow(nxt){
$("#FD"+nxt).remove();
calTotalAmount()

Value condition not working as expected

I have number of inputs and I want to set a minimum value of each input section. For example, I have set a minimum input value of 100. So if the value of any input is less than 100 from all the inputs it will show an error. Otherwise if value of all the inputs is greater than or equal to 100 it will show the success message.
In my case if I enter less than value in an input it will show error but with this less value if I enter greater value in other input it show success message.
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_small" name="custom_small" onkeydown="return myFunction(event);">
</div>
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_medium" name="custom_medium" onkeydown="return myFunction(event);">
</div>
<input type="text" class="custom_large" name="custom_large" onkeydown="return myFunction(event);">
</div>
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
});
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
Please have a look at the code and help me find out the issue
There's a couple of issues.
You should declare total outside the loop otherwise you reset it back to 0 on each iteration.
You should also use a single each() call to loop over a set of elements, as map() is intended to be used to create an array from those elements.
You only need to call parseInt() once when you add the value to total
Your else if condition is redundant and can be replaced by just else, or even a ternary as below.
Try this:
jQuery(function($) {
var total = 0;
$('.selected-input-wrap > input').each(function () {
total += parseInt(this.value, 10);
});
var msg = total >= 100 ? '<p>Success</p>' : '<p>Please select at least 100 for each color</p>';
$(".select-quantity").html(msg);
});
The total variable is looping through all the inputs and only once its returning according to your code. Try closing the each loop after the if-else condition and check once.
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
})
You can use the following jquery code :-
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input').each(function () {
total = $(this).val();
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
}
else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
});
It may help you.
Try this.
var MIN = 100, value = 0;
jQuery('.selected-input-wrap > input').each(function (idx,el) {
value += parseInt(el.value);
});
if (value < MIN) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else {
jQuery(".select-quantity").html('<p>Success</p>');
}
In My Case i have solved the issue as follows:
var total = 0;
var array_total = new Array();
jQuery('.selected-input-wrap > input').each(function(index, value) {
jQuery( ".right-minimu").remove();
var total = jQuery(this).val();
console.log("Total Value : " + total);
if (total != '') {
var t_array = array_total.push(total);
}
console.log('Total Array : ' + array_total);
});
/******** make array unique *************/
var unique_total = [];
jQuery.each(array_total, function(i, el) {
if (jQuery.inArray(el, unique_total) === -1)
unique_total.push(el);
});
var current_urls = jQuery(location).attr('href');
var rest = current_urls.substr(37, 9); //
var current_urls = jQuery(location).attr('href');
var rest_2 = current_urls.substr(37, 18);
var rest_3 = current_urls.substr(37, 15);
var rest_4 = current_urls.substr(37, 8);
jQuery.each(unique_total, function(key, total) {
for (var i = 0; i <= unique_total.length; i++) {
if(rest == "bracelets") {
if (parseInt(unique_total[i]) <= 99) {
jQuery(".select-quantity").css("display", "block");
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
jQuery( "#order-overview-table table" ).css("display" , "none") ;
jQuery( "#order-overview-table").append("<p class='right-minimu'>Please select at least 100 for each color</p>") ;
jQuery('.btn-cart').removeAttr("onclick");
return false;
} else if (parseInt(unique_total[i]) >= 100) {
jQuery(".select-quantity").css("display", "none");
jQuery('.btn-cart').attr('onClick', 'productAddToCartForm.submit(this);');
jQuery(".select-quantity").html('<p>Products Added</p>').delay(4000);
}
}

How to change amount variable is incremented by in JavaScript?

!NO JQUERY!
Ok, so I am making a game for my friends based on cookie clicker game from years ago and my issue is I want to increase what the clicks are incremented by when I click a multiplier button.
Basically, when the user reaches 100 clicks and if they click on the multiplier button it will increase the increment by 1.
The cpcm function function cpcm(){cl1ck5m = 1;} will increase cl1ck5m by 1 when the user clicks the multiplier button. I want to add this value to the main increment total = cl1ck +=1; in the function cl1ckm8() {} only if the user clicks the multiplier button when they reach 100 clicks.
I dont know how I would do this.
var cl1ck5 = 0;
var total = 0;
var cl1ck5m = 0;
var rotated = false;
window.alert("H3lp C00ki3 Man3st3r!\nCan y0u h3lp C00ki3 Man3st3r c0ll3ct c00ki3s?");
function cl1ckm8() {
total = cl1ck +=1;
document.getElementById('cl1ckC0unt').innerHTML = total;
if (cl1ck5 == 90) {
var div = document.getElementById('butt');
var deg = rotated ? 0 : 90;
var msg = document.getElementById("ache");
msg.innerHTML = "nineD d3gr33s";
div.style.transform = 'rotate('+deg+'deg)';
}
if (cl1ck5 == 100) {
var div = document.getElementById('cpcbutt');
div.innerHTML = "1";
}
}
function cpcm(){
cl1ck5m = 1;
}
I'm not sure what you're asking but anyway...
var multiplierButtonClicked = false;
document.getElementById("multiplier").onclick = function(){
if (cl1ck5 >= 100)
multiplierButtonClicked=true;
}
function cl1ckm8()
{
total = cl1ck +=1;
if (multiplierButtonClicked)
total += cl1ck5m;
//...
}
function cpcm(){
if (multiplierButtonClicked)
cl1ck5m += 1;
}
I fixed it. Thanks for any help.
I simply put the multiplier in place of the 1 in total = cl1ck +=1; like total = cl1ck +=cl1ckm;. I was trying to avoid this way to find other ways of doing it but this works best.

Categories