append cells back into table and delete task - javascript

Hello I currently have a script where I append some data into a table then I type into a input and press the add button and that saves all the cells in that table as whatever you typed into the taskName input.
It gets set as localstorage and pops up in two selects one on another html page and one on the html page that it was made in.
the script works well and Im able to call the cells depending on which one I select. The only problem is that I cant delete the task. I want to be able to select the task in the html select and then have it append all the cells into the html page where I can delete all the cells and after I do It removes the task from the localStorage or other words just deletes it completely here is my html code:
<div id="taskContainer">
<table id="items-table">
<!--<caption>Task</caption>-->
<tr>
<th>Item</th>
<th>Size</th>
<th colspan="3">Options</th>
</table>
</div>
<label for="loadTask">Load Task:</label>
<label for="taskName">Task Name:</label>
<select id="loadTask">
<option></option>
</select>
<input type="text" id="taskName"></input>
<button type="submit" id="addTask">Add</button>
and here is my JS:
$(function() {
loadAllTasks();
$("#addTask").click(function() {
let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
// create task object from cells
var task = { cells: cells };
// set name property of the task
task.Name = $("#taskName").val();
// call save method using the new task object
saveTaskInStorage(task);
});
});
function saveTaskInStorage(task) {
// Get stored object from localStorage
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof (savedTasks) !== "object")
savedTasks = {};
// Set the new or exists task by the task name on savedTasks object
savedTasks[task.Name] = task;
// Stringify the savedTasks and store in localStorage
localStorage.setItem('tasks', JSON.stringify(savedTasks));
alert("Task has been Added");
}
function loadAllTasks() {
// Get all saved tasks from storage and parse json string to javascript object
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof (savedTasks) !== "object")
return;
// Get all property name of savedTasks object (here it means task names)
for (var taskName in savedTasks){
$("#loadTask").append('<option>' + taskName + '</option>')
}
}
function loadTaskFromStorage1(taskName) {
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// Return the task by its name (property name on savedTasks object)
return savedTasks[taskName];
}
var tasky = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(tasky.cells);
if ((tasky.cells) = "") {
delete savedTask[taskName]
}
as you can see at the very bottom I have tried to do what I wanted but it didn't work. I changed up to task(y) and loadTaskFromStorage(1) because I already have these functions called in the other html page as (task =) and (loadTaskFromStorage) and they work perfectly fine.
When I try and run the very bottom script it does not recognize the task and says that it is undefined. Am I not able to call localStorage in the same file as I set it? or is there something else I am missing.
I have html code and JS that I missed out its just the inputs and when I press the button it ads there val(); into the table
I want to be able to make tasks and delete them easily.
update:
I added the loadTasksFrom Storage function outside of the function where the task is created then I made a test button the see if that would work:
$(function() {
$("#test-add").click(function() {
var task = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(task.cells);
})
})
when I ran this I got this error:
html.replace is not a function
that pointed to this line:
$("#items-table").append(task.cells);
but when I changed this line to:
alert(task.cells);
I got it to actually alert the cells in the task Which has never happend before so that is huge progress!
the only thing I need to solve now is:
How to get it to append into the table
Be able to add the task into the table just by changing the select (not by clicking button)
be able to delete the task completely from all the selects when I delete it with the small delete buttons that each task gets added with.
another update:
I am able to append task.cells[1][0] with stuff like that but I cant just do task.cells I also dont want to append the so.. How would I append row by row with each X button that is added into each table row something like
.append(task.cells[1][0], task.cells[1][1], task.cells[1][2] etc...
this code above just adds in each cell eight beside each other it doesnt add in the cell under its specific table header. How would I do that.
I appreciate anyone taking the time out of there day to help me out.

With a few code corrections, the code is running without error, yet I am unsure if it is working as intended.
Example: https://jsfiddle.net/Twisty/h901jryt/
JavaScript
$(function() {
loadAllTasks();
$("#addTask").click(function() {
let cells = Array.prototype.map.call($("#items-table")[0].rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
// create task object from cells
var task = {
cells: cells
};
// set name property of the task
task.Name = $("#taskName").val();
// call save method using the new task object
saveTaskInStorage(task);
});
function saveTaskInStorage(task) {
// Get stored object from localStorage
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
savedTasks = {};
// Set the new or exists task by the task name on savedTasks object
savedTasks[task.Name] = task;
// Stringify the savedTasks and store in localStorage
localStorage.setItem('tasks', JSON.stringify(savedTasks));
alert("Task has been Added");
}
function loadAllTasks() {
// Get all saved tasks from storage and parse json string to javascript object
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
return;
// Get all property name of savedTasks object (here it means task names)
for (var taskName in savedTasks) {
$("#loadTask").append('<option>' + taskName + '</option>')
}
}
function loadTaskFromStorage1(taskName) {
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// Return the task by its name (property name on savedTasks object)
return savedTasks[taskName];
}
var tasky = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(tasky.cells);
$.each(tasky.cells, function(k, v) {
if (v == "") {
delete tasky.cells[k];
}
});
});
In your click function, I update some of the JavaScript code to jQuery. Simply for consistency.
In regards to the code you attempted, I used this as a replacement:
var tasky = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(tasky.cells);
$.each(tasky.cells, function(k, v) {
if (v == "") {
delete tasky.cells[k];
}
});
The object tasky is populated with elements, one being cells that is an array of Strings. I assumed you were looking for empty cells. the $.each() is a good way to iterate these. See More: http://api.jquery.com/jquery.each/
The function will run and receive k as the Key and v as the Value from each array element. So for example, if tasky.cells was assigned the following Array:
var tasks = [
"Wake Up",
"Eat Breakfast",
"Help Mom",
"Drive to Work"
"",
"Go to Bed"
];
You would have an array called tasks with 6 keys: 0,1,2,3,4,5; and 6 elements. Using something like:
$.each(tasks, function(k, v){
$("#results").append(k + ": " + v + "<br />");
});
We would see resulting HTML like:
0: Wake Up<br />
1: Eat Breakfast<br />
2: Help Mom<br />
3: Drive to Work<br />
4: <br />
5: Go to Bed
We can use this key value to manipulate the array. To fully remove the element, you might want to consider .splice() versus delete.
$.each(tasks, function(k, v) {
if (v == "") {
tasky.cells.splice(k, 1);
}
});
If we have the above data and perform this operation, the resulting array wil lbe:
[
"Wake Up",
"Eat Breakfast",
"Help Mom",
"Drive to Work"
"Go to Bed"
];
This will also have a re-indexed set of keys. See more: Deleting array elements in JavaScript - delete vs splice
Hope that helps.

Related

Populating table with textbox value from previous HTML page

I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.
This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?
I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).
Here's what I have so far:
HTML for textbox (page 1):
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
JS on page 1:
$('#sales_order_form_button').click(function() {
let table_info = [];
$('input[type=checkbox]').each(
function(index, value) {
if($(this).is(':checked')) {
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
}
);
}
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
JS on page 2:
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
for(let i = 0; i < data_from_page_1.length; i++){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue);
$('#output_table').append(row);
}
// code to sum CPC column
var sum1 = 0;
$("#output_table tr > td:nth-child(2)").each(
(_,el) => sum1 += Number($(el).text()) || 0
);
$("#sum1").text(sum1);
//datetime stamp
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleString();
Output HTML table (page 2):
<table id="output_table">
<tr>
<th>Name</th>
<th>Value</th>
<th>Number of Clicks</th>
</tr>
<tfoot>
<tr>
<th id="total" colspan="1">Total CPC:</th>
<td id="sum1"></td>
</tr>
</tfoot>
</table>
As stated in the #Manu Varghese comment, the way to go would be using sessionStorage or localStorage.
First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:
localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.
That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.
Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.
For that, in the first page you must use:
sessionStorage.setItem("key", "value")
You may set the item right when you perceives a change, like in the input 'blur' event.
and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:
sessionStorage.getItem("key")
Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).
Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.
Implementation in the given case
Your code can be modified in three steps:
Change the way you save the data to use the storage
Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.
Load the JSON object and its fields (the array and the number).
Step 1 - Changing to sessionStorage
Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.
If you want to use the storage rather than the URL for all the data, just change these lines of code from:
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
to the code that will save the data into a (local/session)Storage:
let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page
Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.
Step 2 -- Adding more data to save
Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.
Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:
let table_data = []; // the array you have
$('input[type=checkbox]').each(
... rest of code ...
); // the function that creates the array (I abbreviated it here)
// Creates an object with an array and a number
let jsonObj = {
table_data: table_data,
number_of_clicks: theNumberYouHave/* your variable with the number here */
};
// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";
Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.
In other words, this simply will create an structure like that:
{
number_of_clicks: 5216,
table_data: [
{ name: "...", value: "..."},
{ name: "...", value: "..."},
{ name: "...", value: "..."},
...
]
}
See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.
Step 3 -- Loading data from page 1
For now, you have these two lines of code in page 2 to read data from page 1:
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:
let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number
Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.
You have it with the unique ID "sum1", the you may just:
$("#sum1").text(number_of_clicks);
And you are done!
I highly recommend localStorage and sessionStorage to be used, as per this and this
Page 1 code full source
$('#next_page_button').click(function(){
let table_info = [];
// Do for checkboxes
$('.campaignstrategy input[type=checkbox]').each(
function(index, value){
if($(this).is(':checked')){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'checkbox'
}
);
}
});
$('.campaignstrategy input[type=text]').each(
function(index, value){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'text'
}
);
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
Page 2 Code full source
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
// clear table
$('#output_table').html("");
// generator checboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "checkbox"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
let recordCount = $("<td></td>").text("");
row.append(recordName, recordValue, recordCount); // not used but needed
$('#output_table').append(row);
}
}
// generate textboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "text"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text("");
let recordValue = $("<td></td>").text("");
let recordCount = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue, recordCount);
$('#output_table').append(row);
}
}
ANSWER:
What would be the best way to approach this?
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session

Passing in data from Mongodb to HTML table using javascript using Node.js framework

I'm quite new at using node.js. Right now I'm trying to pull data from MongoDB and display it in a table using Javascript + HTML. However, my table is populating with undefined in all the fields. I think something is definitely wrong with how I'm reading data through to the Javascript function b/c I am able to render the full results from the people.js file straight to the webpage. Thank you in advance!! Below is my code:
Code for my people.js file:
exports.getPeople = (req, res) => {
People.find((err, docs) => {
if (err) { return next(err); }
if (docs != null){
console.log(docs.length)
docs.forEach(function(docs, index) {
console.log(index + " key: " + docs.name)
});
res.render('people', { people: docs });
}
else{
res.render('people', { people: docs() });
}
});
};
My Javascript + HTML that's populating my webpage.
script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js', charset='UTF-8')
script.
$(document).ready(function(){
var obj= '$(people)'
var tbl = "<table>"
var content="";
for(i=0; i<obj.length;i++){
content +=
'<tr>+<td>' +obj[i]["name"]+
'</td><td>'+obj[i]["type"]+
'</td><td>'+obj[i]["min_hours"]+
'</td><td>'+obj[i]["max_hours"]+
'</td><td>'+obj[i]["email"]+
'</td><td>'+obj[i]["phone_number"]+
'</td><td>'+ '<input type="button" value = "Update" onClick="Javacsript:deleteRow(this)">' +
'</td><td>'+'<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
'</td></tr>';
}
content += "</table>"
$('#myTableData').append(content);
});
As you mentioned, you can render the array results from the people.js file directly into the webpage. So, you don't have to read the data through a JavaScript function using jQuery. The template engine language is built on top of JavaScript and it supports plenty of methods and features to do what you're trying to achieve here. So, for example, you may use an iteration method like each..in to build your table (see docs - Iteration):
// ...
body
table(id="myTableData")
// for each person in the people array (from people.js) ...
each person in people
// build a new table row
tr
// insert table data
td #{person.name}
td #{person.type}
td #{person.min_hours}
td #{person.max_hours}
td #{person.email}
td #{person.phone_number}
// add the update and delete buttons
td
input(type="button" value = "Update" onclick=" ... ")
input(type="button" value = "Delete" onclick=" ... ")
// move to next person in the people array ...
The Problem
var obj = '$(people)' does not work as you may expect. You want obj to hold the people array from the people.js file so that you can loop over each object in the array, but this is not what's happening. obj is actually a string value of length 9, so the for loop evaluates 9 string values (not objects). This is why all of your fields are undefined.
To see what I mean, run this code snippet:
var obj = '$(people)';
for (var i = 0; i < obj.length; i++){
console.log(obj[i]);
console.log(obj[i]["name"]);
}
The reason $(people) does not evaluate to an object is mainly because the parent element, script. causes everything below it to evaluate to plain text. The . after the tag causes the template engine to render plain text (see docs: Block in a Tag).
If you wanted to assign people to obj in your inline script you may try it this way:
script
| var obj = #{people};
But this will cause an Unexpected identifier JavaScript error because of the _id field on each item in people. By default _id is an ObjectID hex value from MongoDb so you would have to either remove the _id field from the docs or add quotes to each doc._id so it evaluates to a string. This would all have to be done in person.js before you return the data.
To see what I mean about the Unexpected identifier error, run this code snippet:
// works
var obj = { _id: '583ab33cdaf857b543c76afe',
name: 'john'};
// Error: Unexpected identifier
var obj = { _id: 583ab33cdaf857b543c76afe,
name: 'john'};

How to delete a key within an object in local storage with Javascript and/or Jquery?

In local storage I have an object named favourites and it contains this..
"{
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
}"
How can I delete an object based on its ID (id3333 & id4444 for examples)
I have tried the following along with some other voodoo..
localStorage.removeItem('id3333'); // no errors, no removal
localStorage.removeItem('favourites':'id3333'); // SyntaxError: missing ) after argument list
localStorage.removeItem('favourites[id3333]'); // no errors, no removal
localStorage.removeItem('id3333', JSON.stringify('id3333')); // no errors, no removal
Also, I will need to get the key name to delete based on a variable, so like this..
var postID = 'id3333';
localStorage.removeItem(postID);
or
var objectName = 'favourites';
var postID = 'id3333';
localStorage.removeItem(objectName[postID]);
Is it possible to remove a nested item directly or do I need to retrieve the full object and then delete the item and then set the object back to local storage again?
The closest I can get to deleting anything directly so far is..
localStorage.removeItem('favourites');
But that of course removes the entire object.
You have a a single key and you are acting like there are multiple keys
var obj = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
window.localStorage.favs = JSON.stringify(obj); //store object to local storage
console.log("before : ", window.localStorage.favs); //display it
var favs = JSON.parse(window.localStorage.favs || {}); //read and convert to object
var delKey = "id3333"; //key to remove
if (favs[delKey]) { //check if key exists
delete favs[delKey]; //remove the key from object
}
window.localStorage.favs = JSON.stringify(favs); //save it back
console.log("after : ", window.localStorage.favs); //display object with item removed
With localStorage.removeItem you can only remove top level keys, i.e. keys directly on localStorage.
Because id3333 is on localStorage.favourites you cannot remove it using localStorage.removeItem.
Instead try delete localStorage.favourties['id3333']
Simple, actually: you just delete it. :)
x = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
console.log(x);
delete x.id3333;
console.log(x);
delete does what you're looking for. You could also do something like delete x.id3333.TITLE if you were so inclined. Note also that delete returns true if successful and false if not.
Suppose you set a nested object in localStorage like that
const dataObj = {
uid: {
name: 'robin',
age: 24,
}
}
window.localStorage.setItem('users', JSON.stringify(dataObj));
Now you want to delete the age property. You can't remove it with removeItem native function since it allows to delete from top level.
So you need to get the data first and delete the property you want and set the data again to localStorage with updated value like that
const existingLocalStorage = JSON.parse(window.localStorage.getItem('users') || {});
if(existingLocalStorage['uid']['age']) { // if throws any error, use lodash get fucntion for getting value
delete existingLocalStorage['uid']['age'];
}
window.localStorage.setItem('users', JSON.stringify(existingLocalStorage));

resolving a javascript and database table logic situation

When I query a database table, I get back values "yes" or "no" for records that represent whether an item is present or not (the item is the column name). I want to create a string that represents the products that are available by name (rather than what I am doing now "kitchen table =" + kitchenTable;
I am thinking this can be solved (poorly) by a series of if statements setting variables to either the product name or to "" and then include all variables in the string
var kt;
if (kitchenTable == yes) kt = "kitchen table";
else kt = "";
if (kitchenCabinet == yes) kc = "kitchen cabinet";
else ka = "";
output = kt + ', ' + kc;
There are about 50 items that can be presented to the user, is there a more efficient way of accomplishing this task?? One option is to change how values are entered into the datbase table such that instead of yes, its the item name but this seems like a poorer way to resolve the issue
Of course you don't give all the details about how do you make query so that is an imaginary mockup of a function simulating query
var available = [];
var result = query("kitchen table");
result === "yes" && ( available.push("kitchen table") );
......
var output = available.join();
What you want is actually built into javascript itself.
I would say using an object literal will really simply your life in this situation by organizing your code and turning it into a more readable format.
I would also recommend turning your server data into true and false as this is a standardized way to communicated a Boolean and allows for the method below to work as it does:
// From server response
var results = {
kitchenCabinet: true,
kitchenTable: true
}
// Use this for your storage of all related items
var kitchenProps = {
kitchenCabinet: 'kitchen cabinet',
kitchenTable: 'kitchen table'
}
// Reuse this function for each time your need a new category (masterBathroomProps...)
function getItemDataIfExists(results, hashTable){
'use strict';
var output = 'Your total is: ';
for (var item in results) {
if (!results.hasOwnProperty(item)) return;
if (results[item]) output += 'A '+hashTable[item]+' ';
}
return output;
}
getItemDataIfExists(results, kitchenProps);
Explanation:
You loop through a result set of an object containing keys names and true false values. In the loop, if the keyname's value is true, then use that keyname to access the properties (in this case a string of your choice. The "key" here is that the key names in each object must line up.
Here is a live demo:
http://codepen.io/nicholasabrams/pen/JXXbYz?editors=0010

How to To Delete The data in Localstorage

what I need
I need to toggle image on click.
like if user select favorite choice & then it mark unfavorite image is altered and data is deleted from localstoarge.
html code
<div style="display:block; float:right; width:auto; color:#7c7c7c;">
</div>
js code
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData;
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
eventData = [];
} else {
// Parse the serialized data back into an array of objects
eventData = JSON.parse(localStorage.getItem('eventData'));
//alert(eventData);
$.each(eventData, function(key, value){
//console.log(value);
var imageUrl='http://im.gifbt.com/images/star1_phonehover.png';
//var imageUrl='http://im.gifbt.com/images/star1_phone.png';
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
//$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
});
}
var details={};
details.sess_id=sess_id;
details.name=name;
details.city=city;
details.country=country;
details.event_url=event_url;
// Push the new data (whether it be an object or anything else) onto the array
eventData.push(details);
// Alert the array value
//alert(eventData); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}
problem
I'm new in localstorage I need to know how could I delete data from json string.
I have implemented add to favorite now I need to mark unfavorite.
data is stored:
[{
"sess_id":182104,
"name":"AUTOMECH FORMULA",
"city":"Cairo",
"country":"Egypt",
"event_url":"automech-formula"
},]
To delete data from localstorage you use localStorage.removeItem('itemNam')
example
localStorage.setItem('name','hello');
to delete the name item from the localStorage you use
localStorage.removeItem('name');
BUT IF YOUR QUESTION IS HOW TO DELETE DATA FROM JSON OBJECT THEN YOU HAVE TWO METHODS
1: changing the original json object
delete originalJson.attributeName
originalJson = {name:'myname',age:30};//our object to test with
example :
delete originalJson.age //in this case originalJson.age is no more available
2: don't change the original object and make another copy instead
originalJson2 = JSON.stringify(originalJson);
originalJson2 = JSON.parse(originalJson2);
delete originalJson2.age //originalJson.age is available but originalJson2.age is not available
here is the : jsfiddle
let assume that sess_id is your unique id for events
function unfavorite(sess_id){
var eventData = localStorage.getItem('eventData');
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
console.log('invalid event');
}
eventData = JSON.parse(eventData);
// Keep all without the one with specified sess_id
$.grep(eventData, function(value) {
return value.sess_id != sess_id;
});
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}

Categories

Resources