I'd like to retrieve the name and the date of created tasks. I managed to put the value taskMessage in local storage, but I don't know how to add taskName as well. This is the code I currently have :
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
$('.task-container').append("<li class='item-content' id='" + taskID + "'>" + localStorage.getItem(taskID) + "</li>");
}
$('.floating-button').on('click', function () {
myApp.prompt('', 'Add Task', function (task) {
if (task !== "") {
myApp.prompt('', 'Choose time', function (time) {
var d1 = new Date();
d1.setHours(time, 0, 0, 0);
var hour = d1.getHours();
if (time > 0 && time < 25) {
var d2 = new Date();
var currenttime = d2.getHours();
if (time > currenttime) {
var taskID = "task-" + i;
var taskMessage = hour;
var taskName = task;
localStorage.setItem(taskID, taskMessage);
var newtask = '<li class="item-content ' + taskID + '"><div class="item-inner"><div class="item-title" >' + taskName + '</div><div class="item-after"> ' + taskMessage + ':00</div> </div></li>';
var taskitem = $('#' + taskID);
$('.task-container').append(newtask);
}
else {
myApp.addNotification({
message: 'Please choose a valide time period'
});
}
}
else {
myApp.addNotification({
message: 'Please choose a value between 1 and 24'
});
}
});
}
else {
myApp.addNotification({
message: 'Please enter a valid name'
});
}
});
});
});
First you should get the data into a variable
var getData =
{
"firstData":"data1",
"secondData":"data2",
"thirdData": "data3"
}
Then you can set the above data's in localStorage...
localStorage.setItem('dataKey', JSON.stringify(getData ));
Then get....
var val = localStorage.getItem('dataKey');
Enjoy!!!
If you want to store two different values in localStorage then you can do somrthing like this :
setItem in localStorage two times with different keys.
localStorage.setItem("message", taskMessage);
localStorage.setItem("name", taskName);
Store both the values in an object.
var obj = {
"message": taskMessage,
"name": taskName
}
var val = localStorage.setItem("task", obj);
typeof val: string
Value of val: [object Object]
setItem method convert the input to a string before storing it.
Try this :
// Put the object into storage
localStorage.setItem('task', JSON.stringify(obj));
// Retrieve the object from storage
var val = localStorage.getItem('obj');
console.log('retrievedValue: ', JSON.parse(val));
You can easily store values in localstorage using following example.
//Save the values to Localstorage
localStorage.setItem('first','firstvalue');
localStorage.setItem('second','secondvalue');
//Retrieve the values from localstorage
localStorage.getItem('first')
//"firstvalue"
localStorage.getItem('second')
//"secondvalue"
localStorage saves item key&value as string,so you call setItem with an object/json object,you must serialize json to string by JSON.stringify() method.when you get value you need parse string as json object using JSON.parse() method.
Test
test(`can't retrieve json from localStorage if raw json data saved`, () => {
localStorage.setItem('foo', {foo: 'bar'});
expect(localStorage.getItem('foo')).toEqual('[object Object]');
});
test(`retrieve json value as string from localStorage`, () => {
localStorage.setItem('foo', JSON.stringify({foo: 'bar'}));
let json = JSON.parse(localStorage.getItem('foo'));
expect(json.foo).toEqual('bar');
});
test(`key also be serialized`, () => {
localStorage.setItem({foo: 'bar'}, 'value');
expect(localStorage.getItem('[object Object]')).toEqual('value');
});
test('supports bracket access notation `[]`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage['foo']).toEqual('bar');
});
test('supports dot accessor notation `.`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage.foo).toEqual('bar');
});
Related
I'm trying to sum the values from the key "value" in the object data.
Googled alot but cant figure this out.
My guess is that i'm not retrieving the values from localStorage.
EDIT: And i want to save the summed values to localStorage...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name, bill.value, bill.id, bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill, billVal, id, false);
data.push({
name: bill,
value: billVal,
id: id,
payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t, { value }) => t + value, 0); // ?????
localStorage.setItem("Bills", JSON.stringify(data));
};
function newItem(name, value, id, payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id", id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
i'v tried to add .values before reduce but nothing works:
billsTotals.innerHTML = Object.values(data.value).reduce((t, {value}) => t + value, 0); // ?????
Not sure about your data variable. But the data variable is an array then you could do something like this.
data.reduce((total,{value})=>{
return total +value
},0)
I need to get a value from excel file when status column value is “Y” and I wanted to return the value from Name Column to the calling function and excel sheet contains the data is as follows
Name Number status
YYYY 1234 N
XXXXX 3456 Y
Function I have written like this
var Excel = require(‘exceljs’);
var workbook = new Excel.Workbook();
var selectStatus = ’’;
module.exports = function() {
return actor({
trimSelectName: function() {
workbook.xlsx.readFile("E:/testData.xlsx")
.then(function(sheetName) {
// use workbook
i = 1;
try {
var workSheet = workbook.getWorksheet("trim");
workSheet.eachRow({
includeEmpty: false
}, function(row, rowNumber) {
if (i == 1) {
i = 0;
} else {
currRow = workSheet.getRow(rowNumber);
console.log("Name :" + currRow.getCell(1).value + ", Number :" + currRow.getCell(2).value +
"Select Status :" + currRow.getCell(3).value);
selectStatus = currRow.getCell(3).value;
if (selectStatus == "Y") {
return selectStatus;
}
}
});
} catch (Error) {
console.log(Error);
}
});
},
});
};
But I am trying to the print value from the calling function, I am always getting it as undefined
Calling function:
const selected = trimDataSelection.trimSelectName();
Could you please let me know where could be the issue?
As I see your function returns actor object, I assume you are using steps_file generated by codeceptjs which is used to extend "I" object in order to add your custom functions. So if you want to invoke your custom function from scenario you should call it like this: const selected = I.trimSelectName()
is there a way for me to retrieve the name of a value?
For example:
I want to get the value names highlighted in yellow.
However, right now I can only get:
From my understanding the below code only return the value which is the player's scores.
var childData = childSnapshot.val();
Can I do something like this to get the value name?
var childValueName = childSnapshot.val().name;
This is my java code:
function PrintData()
{
var ref = firebase.database().ref('Score');
var PrintData = document.getElementById('PrintOutData');
ref.on("value", function(snapshot)
{
PrintData.innerText = "";
snapshot.forEach(function(childSnapshot)
{
console.log("childSnapshot.key: " + childSnapshot.key);
var childData = childSnapshot.val();
let keys = Object.keys(childData)
keys.forEach(key => {
let value = childData[key.toString()];
console.log("value: " + value);
PrintData.innerText += childSnapshot.key + ": " + value +"\r";
})
});
});
}
My html code:
<button type="button" onclick="PrintData()">Print!</button>
Please correct me if I am wrong! Thankyou.
See firebase.database.DataSnapshot
key
(string or null)
The key (last part of the path) of the location of this DataSnapshot.
The last token in a Database location is considered its key. For example, "ada" is the key for the /users/ada/ node. Accessing the key on any DataSnapshot will return the key for the location that generated it. However, accessing the key on the root URL of a Database will return null.
// Assume we have the following data in the Database:
{
"name": {
"first": "Ada",
"last": "Lovelace"
}
}
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "ada"
var childKey = snapshot.child("name/last").key; // "last"
});
Firebase has a well versed and beautiful documentation.
According to firebase documentation, datasnapshot is returned when you pass a relative path to the child() method
// Assume we have the following data in the Database:
{
"name": {
"first": "Ada",
"last": "Lovelace"
}
}
// Test for the existence of certain keys within a DataSnapshot
var ref = firebase.database().ref("users/ada");
ref.once("value")
.then(function(snapshot) {
var name = snapshot.child("name").val(); // {first:"Ada",last:"Lovelace"}
var firstName = snapshot.child("name/first").val(); // "Ada"
var lastName = snapshot.child("name").child("last").val(); // "Lovelace"
var age = snapshot.child("age").val(); // null
});
The following may work for your purpose:
firebase.database().ref('score').once('value', snap => {
var data = snap.val() // should return => {User1: {GamePlay00: 3}, User2:
{GamePlay00: 1}, ...}
var users = Object.keys('data') should return // => [User1, User2, ...]
var usersDatas = users.map(user_id => data[user_id]) // should return something like => [{gamePlay00: 3}, {gamePlay00:1}, ...]
var value = usersDatas.map(game_play_id => game_play_id) // should return => [gamePlay00, gamePlay00...]
})
Please refer to these link for further documentation: Object.keys Firebase Docs
I'd stick to using Snapshot.forEach() for the lower level too:
var ref = firebase.database().ref('Score');
var PrintData = document.getElementById('PrintOutData');
ref.on("value", function(snapshot) {
PrintData.innerText = "";
snapshot.forEach(function(userSnapshot) {
console.log("childSnapshot.key: " + userSnapshot.key);
userSnapshot.forEach(function(gameSnapshot) {
PrintData.innerText += gameSnapshot.key + ": " + gameSnapshot.val() +"\r";
})
});
});
I want to save different objects with different key to local storage every time my button clicked. But always key == 0 and records doesn't create, one record in local storage only update,I think this is because key is always same. How I can change this,to put different objects to local storage?
(function() {
window.onload = function() {
var key = 0;
var storage = new Storage();
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
key++;
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
As localstorage API is implemented
You set an item for a keyName (1st argument):
localStorage.setItem(keyName, keyValue);
You get an item for a keyName:
var aValue = localStorage.getItem(keyName);
So in your case your Storage Object should be adapted since it seems like you need multiples keys but your get storage will only retrieve a fixed key='items'.
So, modify your Storage.get and pass a key when you call it:
function Storage() {
this._ITEMS_DESCRIPTOR = 'items'; // I guess a default key?
}
// let key be specified when method is called, or by default set it to the private property _ITEMS_DESCRIPTOR
Storage.prototype.get = function(key) {
var fromStorage = localStorage.getItem(key ? key : this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
your key should be incrementing, but your storage.get is hard coded to a specific key so you'll never be able to retrieve them through its get method.
You should also verify that the method is being invoked
You could try a string vs a number as a key
storage.set("topic_" + key, ticket);
// alert("topic set for topic_" + key);
// retrieve and test data storage
// var data = localStorage.getItem("topic_" + key);
// alert("from storage:\n\n" + JSON.stringify(data));
key++;
Use F12 to review localStorage or simply test the data that is stored
function test(){
if (localStorage.length == 0)
alert("no items in localStorage");
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
var value = localStorage.getItem(key);
alert("storage [" + key + "] = " + value);
}
}
suppose i have below function, which is getting jsonData in the form of jason, i validate the var jsonData to check for NaN ?
function save() {
var jsonData = getEnteredValue();
$.ajax({
type : 'POST',
url : 'saveSalesForecast.json',
data : 'jsonPostData=' + jsonData,
success : function() { //alert("success");
}
});
}
i only know how to replace NAN but don know how to check for NAN!
jsonData = JSON.parse(jsonData.replace(/\bNaN\b/g, "null"));
here is remaining function:(any field values can be string,numbers but it should not be NAN
function getEnteredValue() {
var rowIds = $("#salesForecastGrid").jqGrid('getDataIDs');
var ids=[];
var jsonPostData = "[";
for ( var i = 0; i <= rowIds.length-1; i++) {
$("#salesForecastGrid").jqGrid('editCell', i, 2, false);
var forecastedSales = parseFloat($("#salesForecastGrid")
.jqGrid('getCell', rowIds[i], 'forecastedSales'));
if (!((forecastedSales == "") || isNaN(forecastedSales) || (forecastedSales ==0))) {
if (ids.indexOf(rowIds[i])==-1){
ids.push(rowIds[i]);
}
}
}
for ( var i = 0; i <= ids.length-1; i++) {
var forecastedSales = parseFloat($("#salesForecastGrid")
.jqGrid('getCell', ids[i], 'forecastedSales'));
var id = $("#salesForecastGrid").jqGrid('getCell', ids[i],
'id');
var date = $("#salesForecastGrid").jqGrid('getCell',
ids[i], 'day');
if (id < 0) {
id = 0;
}
var record = "{" + "id:" + id + "," + "date:" + date + ","
+ "forecastedSales:" + forecastedSales + "}";
jsonPostData = jsonPostData + record;
if (i != ids.length) {
jsonPostData = jsonPostData + ",";
}
}
jsonPostData += "]";
return jsonPostData;
}
Json Data like:
"[{id:68447,date:04-17-2014,forecastedSales:8420.42},{id:68448,date:04-18-2014,forecastedSales:9912.68},]"
Your problem is that you are creating the JSON manually, and thus end up with invalid JSON. Do yourself a favor and use JSON.stringify:
function getEnteredValue() {
var rowIds = $("#salesForecastGrid").jqGrid('getDataIDs');
var ids=[];
var data = [];
// ...
for ( var i = 0; i < ids.length; i++) {
// ...
data.push(
{id: id, date: date, forecastedSales: forecastedSales}
);
}
return JSON.stringify(data);
}
Since NaN is not a valid value in JSON, it will automatically be converted to null. Example:
> JSON.stringify({a: NaN});
"{"a":null}"
For more info see Using native JSON.
NaN is not acceptable in JSON. JSON specification does not support NaN as a value. Even when javascript object has NaN value, it will be converted to null when you serialise to JSON format.
First of all, JSON is not an Javascript Object. JSON is general format which can be understand by all languages.