Update total variable when quantity is changed - javascript

I'm having trouble updating the total when I change the "Complete E-Book" product quantity. When I first set the quantity and add it to basket it shows the correct total within the basket but when I change the quantity it adds on to the previous total. Overall I want to be able to add multiple products to the basket total (reason for x += p2Total (x var is what holds the total - Line 86) but while allowing for the Quantity of the product to be changed and then updated in the total.
Codepen Here >
Products in question are the top 2
JS:
// JQuery Functions for NavBar - Class Toggle
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar').toggleClass('animate');
})
})();
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar2').toggleClass('ApprDown');
})
})();
/*
START OF BASKET
START OF BASKET
*/
// Get access to add to basket basket button
var addToBasket = document.querySelector('.atbb');
addToBasket.addEventListener('click', P1);
// Formatter simply formats the output into a currceny format istead of a general number format. This is using the ECMAScript Internationalization API
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2,
});
var totalBasket
var discountLimit = 10
var discount = 3.50
var x = 0.00
// One big function with different condtions based on the differnt products and then simply concatinate the values where needed
function P1() {
var y = document.getElementById("p1Quant").value;
if (+y > discountLimit) {
var z = 15.000
x = parseFloat(+y) * parseFloat(+z); // + will convert the vars into Numbers etc
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
// Jquery Notificaiton
var truckVar = document.getElementById("truck");
truckVar.setAttribute("class", "animateTruck");
} else if (+y <= 0) {
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(0) + ("<br/>") + ("Total: ") + formatter.format(0)
} else {
var z = 15.000
var s = 15.000
x = parseFloat(+y) * parseFloat(+z) + 3.50
var sub = parseFloat(+y) * parseFloat(+s)
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(sub) + ("<br/>") + ("<hr />") + ("Plus £3.50 Delivery") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
}
}
var addToBasket2 = document.querySelector('.atbb2');
addToBasket2.addEventListener('click', P2);
function P2() {
p2Total = 0.00
var y = document.getElementById("p2Quant").value;
var p2 = 8.00
var p2Total = parseFloat(+y) * parseFloat(+p2); // + will convert the vars into Numbers etc
// var totalBasket = + x + x // javascript add value onto set var
x += p2Total // Append the amount to the basket
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
if (+y <= 0) {
p2Total = 0.00
}
}

Don't add the value to x, add x and p2Total into a new temporary value that is scoped to the function itself and use that.
var tmp_total = x + p2Total;
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(tmp_total) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(tmp_total)

Related

search whether id consists of dynamic value

The script below will loop through and generate 50 records. I have a dynamic value RANKS = "8". How can I check if 8 is exists in id="rankN"?
The value[RANKS] is dynamic from 1-50
var RANKS = "8";
var ranking;
for (var i = 0; i < rankingList.length; i++) {
var a = 1;
ranking = "<div > " +
("<div id=rank" + a + " class='RankCol'>" + rankingList[i].rankNo + "</div>") +
("<div>" + rankingList[i].username + "</div>") +
("<div>" + rankingList[i].winningAmt + "</div>") +
("<div> " + rankingList[i].uCoin + "</div>") +
(" </div>");
};
Expected result:
A
A
B
B
C
B
A
A
B
G
so if my ranking is 8, the text will bold. IF the value is not within 50, then i will do another css. my main problem is how can i check whether the looped' ID contains the id number same as my RANKS(which is 8)
If you want to check in DOM, then simply var exists = $('#rank8').length !== 0.
If you want it to check inside loop:
var ranks = {};
for (var i = 0; i < rankingList.length; i++) {
newRank = 'rank' + i;
if (typeof ranks[newRank] !== 'undefined') {
// skip
continue;
} else {
ranking = '<div id="' + newRank + '" ...';
}
ranks[newRank] = newRank;
}
Try this
rankingDiv.html(rankingList.map((rank,i) => `<div>
<div id="rank${i+1)" class='RankCol'>${rank.rankNo}</div>
<div>${rank.username}</div>
<div>${rank.winningAmt}</div>
<div>${rank.uCoin}</div>
</div>`);
const $myRank = $(`#rank${RANKS}`);
if ($myRank.length===1) myRank.html(`<b>${$myRank.text()}</b>`)
Older sugggestion
$(\`#rank${RANKS}\`).length===1

Filter specific properties and sum the values

I have a Leaflet map with polygons, you can click on each polygon to select them and there is an info window "L.control" that shows the values for the selected polygon. As you continue click on polygons the info window add values for each selected and you get total values for all selected polygons. All this is fine but I need to get down to more detailed sum for specific properties like the example below of regions. If ten polygons are selected I want to differentiate the total amount for regions with properties "REGION SOUTH" and "REGION NORTH" as well as the total of all.
This is the code I'm using, to sum the totals of different properties is no problem but how do you sum for defined properties?
How and where can I add a kind of filter solution that sum only the properties I want?
$.each(statesData.features, function(index, feature) {
var name = `${feature.properties.ZIPCODE} ${feature.properties.Name} ( ${feature.properties.average_time} - ${feature.properties.CITY})`
placenames.push(name);
zipcodes[name] = feature.properties.ZIPCODE;
time = feature.properties.average_time
});
etc....
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time, // in seconds
total2 += properties.distance,
total3 += properties.amount, // amount for Region South only
total4 += properties.amount, // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map);
FeatureSelected:
function checkExistsLayers(feature) {
var result = false
for (var i = 0; i < featuresSelected.length; i++) {
if (featuresSelected[i].ZIPCODE == feature.properties.ZIPCODE) {
result = true;
break;
}
};
return result
}
This is part of the json file structure:
var statesData = new L.LayerGroup;
var statesData = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ZIPCODE":12345,"CITY":"LONDON","REGION":"REGION SOUTH","amount":1088,"average_time":26150,"distance":2.2},"geometry":{"type":"MultiPolygon","coordinates":...
I did try the following but that did not work...
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH' )
return true;
}
total4 += filt_north.(properties.amount), // amount for Region North only
The filt_north function you wrote looks good, just add a filt_south filter to get the south region and do:
let filteredResults = featuresSelected.filter(
result => filt_north(result.feature) || filt_south(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
...
Tried your solution, seems it breaks the code and totals is not added up at all = stopped working. I did this, should it be done in a different way?
Filter function:
function filt_south (feature){
if (feature.properties.REGION === 'REGION SOUTH')
return true;
}
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH')
return true;
}
Then changed to this (I must be doing something wrong here):
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
let filteredResults = featuresSelected.filter(
result => filt_south(result.feature) || filt_north(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time,
total2 += properties.distance,
total3 += filt_south (properties.amount), // amount for Region South only
total4 += filt_north (properties.amount) // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map)

Adding multiple number variables returns NaN even though it is already initiated

I'm trying to get the sum of multiple variables and pass it on $total variable. I've declared and initialized all the variables and used parseInt, parseFloat and Number function but to no avail. Please see my codes below:
//gets value from a number slider
var $qty = slider == 1?val:$("#qty").val();
var $qly = slider == 2?val:$("#qly").val();
var $js = slider == 3?val:$("#js").val();
var $psd = slider == 4?val:$("#psd").val();
var $org = slider == 5?val:$("#org").val();
var $coop = slider == 6?val:$("#coop").val();
var $att = slider == 7?val:$("#att").val();
var $punc = slider == 8?val:$("#punc").val();
var $comm = slider == 9?val:$("#comm").val();
var $inter = slider == 10?val:$("#inter").val();
var $ini = slider == 11?val:$("#ini").val();
var $inno = slider == 12?val:$("#inno").val();
var $flex = slider == 13?val:$("#flex").val();
var $total = 0.0;
var $sum = 0.0;
What I have tried:
$total = $qty + $qly + $js + $psd + $org + $coop + $punc + $comm + $inter + $ini+ $inno + $flex;
// returns 7.5555552.52.52.52.52.52.5
$total = Number($qty) + Number($qly) + Number($js) + Number($psd) + Number($org) + Number($coop) + Number($punc) + Number(comm) + Number($inter) + Number($ini) + Number($inno) + Number($flex);
//returns NaN
$total = parseFloat($qty) + parseFloat($qly) + parseFloat($js) + parseFloat($psd) + parseFloat($org) + parseFloat($coop) + parseFloat($punc) + parseFloat(comm) + parseFloat($inter) + parseFloat($ini) + parseFloat($inno) + parseFloat($flex);
//returns NaN
$total = parseInt($qty) + parseInt($qly) + parseInt($js) + parseInt($psd) + parseInt($org) + parseInt($coop) + parseInt($punc) + parseInt(comm) + parseInt($inter) + parseInt($ini) + parseInt($inno) + parseInt($flex);
//returns NaN
$sum = parseFloat($qty) + parseFloat($qly) + parseFloat($js) + parseFloat($psd) + parseFloat($org) + parseFloat($coop) + parseFloat($punc) + parseFloat(comm) + parseFloat($inter) + parseFloat($ini) + parseFloat($inno) + parseFloat($flex);
$total = parseFloat($sum);
//returns NaN
What am I doing wrong or did I miss something?
While getting $total ,you need to parse all individual value to number , then you won't get NaN.
$total = $qty + $qly + $js + $psd + $org + $coop + $punc + $comm + $inter + $ini+ $inno + $flex;
// returns 7.5555552.52.52.52.52.52.5
The return value has many decimal because they are treated as string and get appended.
Also change like this.
var $qty = slider == 1 && !isNaN(parseFloat($("#qty").val()))?val:parseFloat($("#qty").val());

ChartJS: Show all tooltips with Total for Multi Pie chart

I have a Pie chart with multiple rings and created a Custom Tooltips function with below code:
function tooltipWithTotalP(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var values = data.datasets[tooltipItem.datasetIndex].data;
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var total = 0;
for (var i in values) {
total += values[i];
}
var percentage = Math.round((value / total) * 100);
var totally = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
return label + " : " + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' (' + percentage + '%)';
} else {
return [label + " : " + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' (' + percentage + '%)', "Total : " + totally];
}
}
The above function is expected to show all the Label values with Total at bottom from the PieChart, but it is showing only individual Values from First Dataset and individual values + Total from second Dataset.
Individual lebels are showing as Undefined.
Here is the JSfille https://jsfiddle.net/kingBethal/x03w2qbk/40/
To see every label remove the tooltipItem.index
var label = data.datasets[tooltipItem.datasetIndex].labels;
To list all the labels in the tool tip is straight forward.
var label = [];
for (var j in labels) {
var percentage = Math.round((values[j] / total) * 100);
label.push (labels[j] + " : " + values[j].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ' (' + percentage + '%)');
}
label.push("Total : " + totally)
return label;
Label color is derived from the datasetIndex so the label background colour doesn't propagate, you will have to create a custom tooltip or disable displayColors.
custom: function(tooltip) {
tooltip.displayColors = false;
},
https://jsfiddle.net/drillep/xb4g19en/2/
The label variable in the label function needs an array index.
var label = data.datasets[tooltipItem.datasetIndex].labels[tooltipItem.index];
https://jsfiddle.net/drillep/40htzrdn/

Convert JSON number to stars

Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});

Categories

Resources