How to update Shopping Cart Total properly in Javascript? - javascript

I am looking for some Javascript that will:
Update Cart Total on products selected (drop-down menu) and quantities entered
(*Security will be handled by back-end PHP. I have attempted this over the last three days but apparently my code was so bad I feel ashamed to repost it here again)
My Thinking:
- Create a cart object
- Make a function that recalculates the total on any changes that occur
(I can not think of anything else this would require given the javascript will just be passing this over to a PHP script to check anyway)
Does anyone know of some javascript that does the job I seek? Is my thinking correct?

Below is sample shopping cart javascript object built using revealing module pattern.
var shoppingCart = function () {
var obj = {}, items = [];
obj.AddItem = function (itemNo, quantity, price) {
var item = {};
item.itemNo = itemNo;
item.quantity = quantity;
item.price = price;
items.push(item)
};
obj.GetAllItems = function () {
return items;
};
obj.GetItemByNo = function (item) {
for (var i = 0; i < items.length; i++) {
if (items[i].itemNo === item)
return item[i];
}
return null;
};
obj.CalculateTotal = function () {
var total = 0;
for (var i = 0; i < items.length; i++) {
total = total + (items[i].quantity * items[i].price);
}
return total;
};
return obj;
};
var cart = new shoppingCart();
Add items using AddItem method, include additional properties that are useful in the UI.
shoppingcart.AddItem(2,4,2.4);
Gets list of items in the shopping cart
var items = shoppingcart.GetAllItems();
Calculates total price of items in shopping cart
var total = shoppingcart.CalculateTotal();
Please note that I have typed this code in here, so might contain typo's and also I recommend having data type validations for price and quantity as numerics before adding item.

Related

Objects array in Javascript

I'm studying Javascript and I have this sample program that shows how to use a module.
There is a "products" array and I couldn't find out what "products[productName]" is meant to do in this program. If I understand correctly, in Javascript, an array always uses numbered indexes and doesn't work if you use named indexes.
As much as I expect, like this objects array is made in this program.
products = [ {productName: 0,} ]
I'm looking forward to helping me. Thank you in advance.
var store = {};
shop.cart = (function() {
var products = [];
function addProduct(productName) {
if(!products[productName]) {
// If the product is not added into the shopping cart, add it there.
products[Productname] = 0;
}
// Raise the number of products by one
products[productName]++;
}
function totalProducts() {
var amount = 0;
for(var productName in products) {
amount += products[Productname];
}
return amount;
}
// interface
return {
add: addProduct,
productAmount: productTotal
};
})();
store.cart.add("keksi");
store.cart.add("keksi");
store.cart.add("apple");
console.log(store.cart.productAmount()); // 3

Sum the values from two functions and add them together

I'm not sure how best to ask this question, I'm new to Javascript and although I have got this far, I don't know how to shorten the code anymore than I have to make it easier to read so...
Here's my code:
var price;
function getInkPrice(arrayOfArrays){
var inkName = 'Epson S60600';
columnNumber = 7;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var inkPrice = document.getElementById("ink-price");
showPrice(inkPrice, arrayOfValues, columnNumber, inkName);
}
function getMileagePrice(arrayOfArrays){
var mileageName = 'Mileage';
columnNumber = 1;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var mileagePrice = document.getElementById("mileage-price");
showPrice(mileagePrice, arrayOfValues, columnNumber, mileageName);
}
function showPrice(el, arrayOfArrays, col, obj) {
const results = arrayOfArrays.filter(r => r[0] === obj);
const newResult = results [0][col].toFixed(2);
el.textContent = newResult;
price = newResult;
combinePrice()
}
function combinePrice() {
alert('your total price is ' + price + price);
}
RESULTS
getInkPrice = 4.19
getMileagePrice = 0.55
Basically the getInkPrice() and getMileagePrice() setups the next function showPrice() to filter the results that I require.
The showPrice() function then filters the results and adds them to a div allowing me to display them in my html page.
Finally I created a global variable called 'price'. Once getMileagePrice() has finished, it calls the combinePrice() function which alerts the combined price (or it will do once I figure this out).
So, the combinePrice() function currently displays:
your total price is 4.194.19
That is wrong, it should display:
your total price is 4.74 (which is the 4.19 + 0.55).
I understand what part of the problem is but I can't figure to how I go about fixing it.
So my showPrice() function is doing the hard work in getting the values, it then stores that in the price variable. How does the price variable know what the value is seeing as both the getInkPrice() and getMileagePrice() are using it so it defaults to the first value.
So my global variable stores the 4.19 from the first function and not getting the value form the second function. Finally the 4.19 is not being classed as a number and therefor not adding them together. I could be wrong though.
Any ideas how I can fix this?
There are two issues here:
When you do 'your total price is ' + price + price, the pluses are evaluated from left to right, so even the second + is actually string + rather than number +. You can solve this issue by doing 'your total price is ' + (price + price).
You have only one variable price, but you seem to need two separate ones, one for ink and the other one for mileage.
Possible solution:
Define price where you will sum results of your functions
Reset price value (to zero) each time before getInkPrice & getMileagePrice called
Add new result value to price inside of showPrice instead of redefining it
Get sum from price whereever you need
var price; // [1]
price = 0; // [2] reset value somewhere before getInkPrice & getMileagePrice called
function getInkPrice(arrayOfArrays){
var inkName = 'Epson S60600';
columnNumber = 7;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var inkPrice = document.getElementById("ink-price");
showPrice(inkPrice, arrayOfValues, columnNumber, inkName);
}
function getMileagePrice(arrayOfArrays){
var mileageName = 'Mileage';
columnNumber = 1;
arrayOfValues = arrayOfArrays.filter(function(r){return true;});
var mileagePrice = document.getElementById("mileage-price");
showPrice(mileagePrice, arrayOfValues, columnNumber, mileageName);
}
function showPrice(el, arrayOfArrays, col, obj) {
const results = arrayOfArrays.filter(r => r[0] === obj);
const newResult = results [0][col].toFixed(2);
el.textContent = newResult;
price += newResult; // [3] add to total price
combinePrice();
}
function combinePrice() {
alert('your total price is ' + price); // [4] get it when you wish
}

How to iterate through javascript object and run a function on each value

I am new to JS.
I set up a Saved Search in NetSuite that gives us the image fields (containing URLs) of our items. I am now setting up a script in NS which tests these fields to see what item fields return 404 (i.e. need to be fixed).
My question is, how to set up function imageURLValidator to iterate through the field values of function searchItems?
Below is my start to the process but obviously has much incorrect syntax.
function imageURLValidator() {
var searchResults = searchItems('inventoryitem','customsearch529');
var url = '';
var item = '';
var field = '';
//insert loop here to iterate over items in searchResults array
//loop through items
for (var i = 0, i > searchResults[inventoryObject].length, i++) {
item = searchResults.[inventoryObject].[i];
//loop through fields in item
for (var f = 2, f > item.length, f++) {
field = item[f];
//check URL via item field's value
var code = checkURL(item[field].getvalue([field]));
//generate error based on code variable
createErrorRecord(code,item,field)
}
}
}
function searchItems(type, searchid) {
//defining some useful variables that we will use later
var inventoryArray = [];
var count = 0;
//loading the saved search, replace the id with the id of the search you would like to use
var inventoryItemSearch = nlapiLoadSearch(type, searchid);
//run the search
var inventoryItemResults = inventoryItemSearch.runSearch();
//returns a js array of the various columns specified in the saved search
var columns = inventoryItemResults.getColumns();
//use a do...while loop to iterate through all of the search results and read what we need into one single js object
do {
//remember the first time through the loop count starts at 0
var results = inventoryItemResults.getResults(count, count + 1000.0);
//we will now increment the count variable by the number of results, it is now no longer 0 but (assuming there are more than 1000 total results) will be 1000
count = count + results.length;
//now for each item row that we are on we will loop through the columns and copy them to the inventoryObject js object
for (var i=0; i<results.length; i++){
var inventoryObject = {};
for (var j=0; j<columns.length; j++){
inventoryObject[columns[j].getLabel()] = results[i].getValue(columns[j]);
}
//then we add the inventoryObject to the overall list of inventory items, called inventoryArray
inventoryArray.push(inventoryObject);
}
//we do all of this so long as the while condition is true. Here we are assuming that if the [number of results]/1000 has no remainder then there are no more results
} while (results.length != 0 && count != 0 && count % 1000 == 0);
return inventoryArray;
}
function checkURL(url) {
var response = nlapiRequestURL(url);
var code = response.getCode();
return code;
}
function createErrorRecord(code,item,field) {
if (code == 404){
//create error record
var errorRecord = nlapiCreateRecord('customrecord_item_url_error');
errorRecord.setFieldValue('custrecord_url_error_item', item);
errorRecord.setFieldValue('custrecord_url_error_image_field', field);
}
}
Here I can see searchResults variable will be empty while looping. As your call to searchItems function is async. Which will take some time to execute because I guess it will fetch data from API. By the time it returns value, your loop also would have bee executed. You can test this by putting an alert(searchResults.length) or console.log(searchResults.length). For that you need to use callback function
Also even if you get the results in searchResults. The loop you are doing is wrong. The array you will get is like [{},{},{}] i.e. array of objects.
To access you'll need
for (var i = 0, i > searchResults.length, i++) {
var inventoryObject = searchResults[i] // your inventoryObject
for(var key in inventoryObject){
item = inventoryObject[key]; // here you will get each item from inventoryObject
//loop through fields in item
for (var f = 2, f > item.length, f++) {
field = item[f];
//check URL via item field's value
var code = checkURL(item[field].getvalue([field]));
//generate error based on code variable
createErrorRecord(code,item,field)
}
}
}
And yes welcome to Javascript

Add values to the cookie using URL

I'm working on my webshop and since I dont want users to have to register to use the webshop, im using javascript cookies to hold the values the user has entered. But I want people who go to the webshop with a different url (for example: http://test.com/index.php?124&342), having 2 values in the cart, I made some functions to work on this. Here is the following code:
function getUrlVars() {
var variabelen = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
var urls = $.cookie($.cookie('cart')) || [];
for (var i = 0; i < variabelen.length; i++) {
urls.push(variabelen[i]);
}
}
if ($.cookie('cart')) {
var Orders = $.parseJSON($.cookie('cart'));
} else {
var Orders = new Array;
}
getUrlVars();
Where "orders" is the json array with the selected product-ID's. Now this is not working as I wanted to. It's not pushing the URL variables into the cart.
Okay UPDATE:
I succeed in pushing the URL variables in the cookie, but now the following problem accurs.
function UpdateTotals() {
ToAddHTML = '<h1>Cart</h1></br>';
console.log(Orders);
TotalPrice = 0;
for (var i = 0; i < Orders.length ; i++) {
var Result = SubMenuItems.filter(function(v) {
return v.submenu_id === Orders[i];
})[0];
TotalPrice += parseFloat(Result.price);
ToAddHTML += '<div class=orderd> <span class="order" Orders='+i+'> </span>'+'€'+zoekresultaat.price+' '+zoekresultaat.title+'</br></div><hr>';
}
The live website is on(nb. im using dutch description so the functions have different names):
Website
If I understand the problem correctly this should do the trick:
// Given: page.html?109&10
// -----------------------
// Split the query string on '&', after the '?' and push
// each value into the array 'Bestellingen'
// -----------------------
$.each(document.location.search.substr(1).split('&'),function(key,value){
Bestellingen.push(value);
});
You can replace your method haalUrlVars with the two lines above and you should find that items 109 & 10 are added to your list as though the were in the cookie when the page loaded.
Does that help?

Sort document collection by values total in xpages

I'm working on an xpages application in which I would like to display the top5 of the total volumes per client.
I have a list of customers who buy any number of products.I would like to classify customers according to the total volume of products purchased.
I use the "Top5" View categorized by customer.
I used a document collection to calculate the total volume by customer.
I get to classify volumes in descending order and select the top 5.But this does not allow me to retrieve the name of the product and the client from the view.
var cls3 = #DbColumn("","Top5",1);
sessionScope.put("clientsList3",cls3);
var db=session.getCurrentDatabase();
var view7=db.getView("Top5")
var dataa =[] ;
var top =[];
for(var r = 0; r < clientsList3.length; r++){
var Cli = #Trim(#Text(clientsList3[r]));
var VolumeTotal :NotesDocumentCollection = view7.getAllDocumentsByKey(Cli);
var vola = 0;
var array = new Array();
var prod = "";
if (VolumeTotal == 0) {array = 0;}
else{
var doca = VolumeTotal.getFirstDocument();
while (doca != null)
{vola = vola + doca.getItemValueInteger("TotalVolume_Intermediate");
doca = VolumeTotal.getNextDocument(doca);
}
array.push(vola);
}
dataa[r] = array;
dataa.sort(function(a, b) {return b - a;});
top = dataa.slice(0,5);
}
return dataa;
}
You do want to use a managed bean for that, it makes a lot of things much easier. You create a custom class that does the compare operation for you:
public Class TopSeller implements Comparable {
String product;
public String getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
// Add properties as needed
public int compareTo(Topseller theOther) {
// Your ranking code goes here
}
}
In that class your compareTo function does provide the ranking and ordering. Then you just need:
Set<TopSeller> allSeller = new TreeSet<TopSeller>();
... and you are done. The Treeset will provide the ready sorted result and you just bind it to a repeat with 5 rows to display

Categories

Resources