localStorage issue - Items not displayed (JSON/JQUERY) - javascript

I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?

something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!

Related

Javascript - setValue returns #ERROR into a cell

I'm really new to Javascript and pretty much copied most of the code and modified it a bit. Sometimes I'm getting an error putted into a cell and sometimes the correct values. Do you know what is the issue?
for (p=3; p < 19; p=p+3){
var Value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(9,p);
var outputValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),(3 + a));
outputValue.setValue(Value.getValue());
a = a +1;}
I'm adding the whole code as well for reference:
function getData() {
var queryString = Math.random();
var i;
for (i=2; i < 8; i++) {
var AddressColumn = SpreadsheetApp.getActiveSheet().getRange("W1").getColumn();
//if (ValueCrypto>0)
var cellFunction1 = '=Value(Replace(IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange(i,AddressColumn).getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange(1,AddressColumn).getValue() + '"),1,1,))*X1';
SpreadsheetApp.getActiveSheet().getRange(i,3).clearContent(); // You can also use range.setFormula("");
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSheet().getRange(i,3).setValue(cellFunction1);
var cellFunction2 = '=Value(Replace(IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange(i,AddressColumn).getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange(1,AddressColumn).getValue() + '"),1,1,))';
SpreadsheetApp.getActiveSheet().getRange(i,8).clearContent(); // You can also use range.setFormula("");
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSheet().getRange(i,8).setValue(cellFunction2);
}
//var cellFunction2 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A4').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A5').getValue() + '")';
//SpreadsheetApp.getActiveSheet().getRange('C2').setValue(cellFunction2);
counter2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A12").getValue();
SpreadsheetApp.getActiveSheet().getRange("A12").setValue(counter2+1)
if (counter2 = 3) {recordValue();}
}
function recordValue() {
SpreadsheetApp.getActiveSheet().getRange("A12").setValue(0);
var counter = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A13");
//console.log(counter)
var dateCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),2);
dateCell.setValue(new Date());
//const errorValues = ["#N/A", "#REF", "#ERROR!"];
var a = 0;
for (p=3; p < 19; p=p+3){
var Value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(9,p);
var outputValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),(3 + a));
outputValue.setValue(Value.getValue());
a = a +1;
}
var TotalValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("R2");
var outputTotalValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),17);
outputTotalValue.setValue(TotalValue.getValue());
var TotalValue2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("R5");
var outputTotalValue2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),18);
outputTotalValue2.setValue(TotalValue2.getValue());
counter.setValue(counter.getValue() + 1);
if(counter.getValue() > 300){counter.setValue("14");}}

Javascript how to define an object by array of objects

I recently started learning html/javascript and I want a temporary object to be filled with one of the objects from an array based on the current page number.
loadnextpage();
function loadnextpage() {
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' + curpage.title);
}
But when I try to run the code it keeps giving me an error message that curpage is undefined, after that it keeps running and thus the last line of code gives an error, when I ask for curpage.pageNumber. After that it stops running the code.
image clipping of my code with error message
What am I doing wrong?
edit:
here is the entire code:
var pagenumber = 0;
var receipt = [];
var price = 0;
var text = '{"page": [{"pageNumber": "1","title": "kies je formaat","optionName": "size","option": [{"text": "klein","value": "small","extraPrice": "100"},{"text": "middel","value": "medium","extraPrice": "200"},{"text": "groot","value": "large","extraPrice": "300"}]},{"pageNumber": "2","title": "kies je kleur","optionName": "colour","option": [{"text": "rood","value": "red","extraPrice": "10"},{"text": "groen","value": "green","extraPrice": "20"},{"text": "blauw","value": "blue","extraPrice": "30"}]}]}';
var allcontent = [];
allcontent = JSON.parse(text);
var imgpath = 'img/';
loadnextpage();
function loadnextpage(){
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' +
curpage.title);
var radiobuttons = '';
var radiobuttonid = [];
for(var i = 0; i < curpage.option.length; i++) {
var curradio = curpage.option[i];
radiobuttons += '<label><div class="selection-wrap">';
radiobuttons += curradio.text;
radiobuttons += ' <input type="radio" name="';
radiobuttons += curpage.optoinName;
radiobuttons += '" value="';
radiobuttons += curradio.value;
radiobuttons += '" id="';
radiobuttons += curpage.optoinName;
radiobuttons += '_';
radiobuttons += curradio.value;
radiobuttons += '"></div></label></br>';
radiobuttonid.push(curpage.optoinName + '_' + curradio.value)
}
changeDiv('choices', radiobuttons);
for(var i = 0; i < radiobuttonid.length; i++){
document.getElementById(radiobuttonid[i]).onclick = function(){
receipt[pagenumber-1] = curpage.option[i];
for(var i = 0; i < receipt.length; i++){
price += receipt[i].extraPrice;
}
changeImg('previewimg', imgpath + curpage.option[i].value +
'/preview.jpg');
changeDiv('previewprice', '<h1>€' + price + ',-</h1>');
};
}
};
function changeDiv(id, content) {
document.getElementById(id).innerHTML = content;
};
function changeImg(id, img){
document.getElementById(id).src = img;
};

How to remove empty values from array in google docs script

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

Issue with multidimensional array

I am having an issue with this darn array. It was to post my info looking like this. Any ideas how to fix this?
prdpr=10.95^TBCC9^2^Shoes
prdsku=2.50^TDxa2^1^Pants
prdqn=7.50^Tasds^1^Hats
prdcatid=undefined^undefined^undefined^undefined
What it should look like is:
prdpr=10.95^2.50^7.50
prdsku=TBCC9^TDxa2^Tasds
prdqn=2^1^1
prdcatid=Shoes^Pants^Hats
Later I'll just string together for a URL
var advid = "xxx";
var oid = "xxx";
var amt = "20.95";
// This array I cannot mess with, this is just an example
var OrderDetails = new Array();
OrderDetails[0] = ['10.95','2.50','7.50'];
OrderDetails[1] = ['TBCC9','TDxa2','Tasds'];
OrderDetails[2] = ['2','1','1'];
OrderDetails[3] = ['Shoes','Pants','Hats'];
var prdpr = '';
var prdsku = '';
var prdqn = '';
var prdcatid = '';
for(var x = 0; x < OrderDetails.length; x++) {
var delim = "";
if(x == 0){
delim = "";
} else{
delim = "^";
}
prdsku += delim + OrderDetails[x][0];
prdpr += delim + OrderDetails[x][1];
prdqn += delim + OrderDetails[x][2];
prdcatid += delim + OrderDetails[x][3];
}
var output = '<div>Product Sku=' + prdsku + 'Item Cost=' + prdpr + 'Quanty=' + prdqn + 'Category=' + prdcatid + '</div>';
document.write(output);
var OrderDetails = new Array();
OrderDetails[0] = ['10.95','2.50','7.50'];
OrderDetails[1] = ['TBCC9','TDxa2','Tasds'];
OrderDetails[2] = ['2','1','1'];
OrderDetails[3] = ['Shoes','Pants','Hats'];
var delim = '^';
var prdpr = OrderDetails[0].join(delim);
var prdsku = OrderDetails[1].join(delim);
var prdqn = OrderDetails[2].join(delim);
var prdcatid = OrderDetails[3].join(delim);

JScript Array issue

Reposted working code
(I'm trying to get Arrays from my ActiveX component, but with no luck. When I run the script I get empty Message Box, but I know that the Array are there:)
var objMain, objAdapt, lgCount, stMsg = "";
objMain = new ActiveXObject("nnetcom.oMain");
objMain.UnlockComponent("xxx-xxxxx-xxxxx-xx");
objAdapt = new ActiveXObject("nnetcom.oNetworkAdapter");
objAdapt.GetNetworkAdapters(); // Collects Network Adapters
vrAdapters = objAdapt.cName; // cName holds collected Network Adapter names
var vrAdaptVB = new VBArray(vrAdapters);
var vrAdaptJS = vrAdaptVB.toArray();
for (lgCount in vrAdaptJS) {
stMsg = stMsg + vrAdaptJS[lgCount] + '\r\n';
}
WScript.Echo(stMsg);
objAdapt = null
objMain = null
var vrAdaptVB = new VBArray(vrAdapters);
var vrAdaptJS = vrAdaptVB.toArray();
stMsg = "";
for (lgCount = 0; lgCount < vrAdaptJS.length; ++lgCount) {
stMsg = stMsg + vrAdaptJS[lgCount] + '\r\n';
}
Per Hans comment,
for (lgCount in vrAdapt)
{
stMsg = stMsg + vrAdapt[lgCount] + '\r\n';
}
should be:
for (lgCount in vrAdapt)
{
stMsg = stMsg + lgCount + '\r\n';
}
as lgCount is the element, not the index.
My Mistake. This example works:
var list = {a:1,b:2,c:3,d:4,e:5};
var msg = "";
for (i in list) {
msg = msg + list[i];
}
//msg = 12345
msg = "";
for (i in list) {
msg = msg + i;
}
//msg = abcde
var list = [1,2,3,4,5];
msg = "";
for (i in list) {
msg = msg + i;
}
//msg = 01234
msg = "";
for (i in list) {
msg = msg + list[i];
}
//msg = 12345
Or simplest way from my first posted answer would be:
var vrAdaptVB = new VBArray(vrAdapters);
var vrAdaptJS = vrAdaptVB.toArray();
stMsg = "";
for (lgCount in vrAdaptJS) {
stMsg = stMsg + vrAdaptJS[lgCount] + '\r\n';
}
This example also works fine for me!

Categories

Resources