I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you
Related
I am getting the data not in the right column. What is the right way to do this?
//store the data into localStorage
/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" +
JSON.parse(localStorage.getItem(key)) + "</td></tr>\n";
}
if (list == "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store shopping list as your browser do not support local storage');
}
}
/*
* Checking the browser compatibility.
*/
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// we can use localStorage object to store data
return true;
} else {
return false;
}
}
/* dynamically draw the table, this is the part that I m not getting it right. What should I do to ge the value in the right column. */
After you parse the JSON, you need to extract the data and item so you can show them in separate table columns.
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Name</th><th>Value</th><th>Item</th></tr>\n";
var i = 0;
if (localStorage.length == 0) {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td><td><i>empty</i></td></tr>\n";
} else {
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
let data = JSON.parse(localStorage.getItem(key));
list += "<tr><td>" + key + "</td>\n<td>" +
data[0] + "</td>" + data[1] + "</tr>\n";
}
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store shopping list as your browser do not support local storage');
}
}
I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(inputbox.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
This will basically make a list when you hover over a certain string. The list will be based on the localstorage and make an inputbox for each point of that list.
The problem is the adding of eventlisteners. For some reason it always returns an empty value when the event is triggered of that inputbox.
function changeAmountProd(inputboxId) {
var products = JSON.parse(localStorage["products"]);
value = document.getElementById(inputboxId).value;
if(value < 1) {
return;
}
products[i].amount = value;
localStorage["products"] = JSON.stringify(products);
makeUL();
}
The problem is with the callback of your change event. You're referring to the changed element using the inputbox variable (that is available through the closure) but by the time your callback is invoked, inputbox will always point to the last generated element.
Try this instead:
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
See addEventListener
Try this:
function makeUL() {
var products = JSON.parse(localStorage["products"]);
var list = document.createElement('ul');
for(var i = 0; i < products.length; i++) {
if(products[i].amount == 0) {
continue;
}
// Create the list item:
var item = document.createElement('li');
var product = products[i];
var totalPrice = product.amount * product.price;
var toDisplay = product.name + " " + product.amount + " #" + totalPrice + " ";
// Set its contents:
item.appendChild(document.createTextNode(toDisplay));
var inputbox = document.createElement("input");
inputbox.setAttribute("id", "inputboxProduct" + i);
inputbox.addEventListener("change", function(){
changeAmountProd(this.id);
});
item.appendChild(inputbox);
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
I have fetched a list of items from web service, now i want to store the item_name on which I have clicked. I cannot store that item name, if its "bread butter" , it stores only "bread".
What shall i do now?
<script>
var sub_catidall = [];
var sub_catnameall = [];
function selected_index(sub_cat_name_all) {
alert("selected sub category" + sub_cat_name_all);
//window.localStorage.setItem("current_sub_id_all",sub_cat_id_all);
window.localStorage.setItem("DishName", sub_cat_name_all);
window.open("MenuDetails.html", "_self");
}
function jsondata(data) {
var parsedata = JSON.parse(JSON.stringify(data));
var sub_category = parsedata["Item List"];
for (var i = 0; i < sub_category.length; i++) {
var sub_menuall = sub_category[i];
sub_catidall = sub_menuall['menuItemId'];
sub_catnameall = sub_menuall['menuItemName'];
//alert(sub_catnameall);
var id = document.createElement("table");
if ((i % 2) == 0) {
id.innerHTML += '<br><td><strong><font face="DEVROYE">' + sub_menuall['menuItemName'] + '</td></strong>';
document.getElementById("block_left").appendChild(id);
} else {
id.innerHTML += '<br><tr><td><strong><font face="DEVROYE">' + sub_menuall['menuItemName'] + '</td></strong>';
document.getElementById("block_right").appendChild(id);
}
}
}
jsonp("http://remoteaddress/hotelTab/menuitem.php?callback=jsondata&mCatId=" + window.localStorage.getItem('current_id') + "&menuCategoryId=" + window.localStorage.getItem('current_sub_id'));
</script>
DOM Storage Guide
Example
var string = 'Bread Butter';
localStorage.setItem("DishName", string);
alert(localStorage.getItem('DishName'));
On jsFiddle
I use Amplifyjs store library to access local storage.
It's simple to use/understand, works really well and it's cross browser (mobile browser as well)
Hope this Helps
I am trying to call two functions when only the "add" button is clicked. the problem I am having is that the final four textboxes in the calculate_balances function are not outputting their variables.
var $ = function (id) {
return document.getElementById(id);
}
// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
// Function to print results to text area //
var update_results = function () {
var list = ""; // string variable to build output //
// check to see if arrays are empty //
if (transactions[0].length == 0) {
$("results").value = "";
} else {
list = "";
// for loop to cycle through arrays and build string for textarea output //
for (var i = 0; i < transactions[0].length; i++) {
list += transactions[0][i] + " " + transactions[1][i] + " " + transactions[2][i] + "\n";
}
// display results //
$("results").value = list;
}
}
// function to gather inputs //
var add_transaction = function () {
$("add").blur();
transactions[0][transactions[0].length] = $("date").value;
transactions[1][transactions[1].length] = $("transType").value;
transactions[2][transactions[2].length] = parseFloat( $("amount").value);
update_results();
calculate_balances();
}
// function for Calculations //
var calculate_balances = function () {
var startBal = 2000.00;
var ttlDeposits = 0;
var ttlWithdrawals = 0;
var endBal = startBal;
if (transactions[1][transactions[1].length] == "deposit")
{
ttlDeposits += transactions[2][transactions[2].length];
endBal += ttlDeposits;
}
if (transactions[1][i] == "withdrawal")
{
ttlWithdrawals += transactions[2][transactions[i]];
endBal -= ttlWithdrawals;
}
$("balStart").value = parseFloat(startBal);
$("ttlDeposits").value = parseFloat(ttlDeposits);
$("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
$("balEnd").value = parseFloat(endBal);
}
window.onload = function () {
$("add").onclick = add_transaction, calculate_balances;
update_results();
}
tHank you
Edit: Did not realize the OP was NOT using jQuery. Your onclick should look like this:
$("add").onclick = function(){
add_transaction();
calculate_balances();
};
The rest here is for jQuery which is not what the OP wanted.
For setting the value of a text box with jQuery use the val() method:
$("balStart").val(parseFloat(startBal));
To call the two methods when the button is clicked:
$("add").click(function(){
add_transaction();
calculate_balances();
});