Auto Saving HTML form in Session Storage in AngularJS - javascript

I have an app which contains a HTML form, the form uses AngularJS meaning textfields use ng-model to save data into objects within the $scope.
Example:
In HTML:
<input type="text" ng-model="user.firstName">
In the controller:
$scope.user = {}
Now what I am trying to do is auto save user data as they type it within the session storage so if the page gets reloaded/refresh accidentally the data is still there and they don't have to type it all again.
I have tired this:
<textarea type="text" class="form-control" id="Background" name="Background" ng-model="obj.background" ng-change="autosave()" required></textarea>
In the above code I have ng-change function that runs when the state of the text field changes.
$scope.autosave = function(){
$window.sessionStorage.setItem("autosave", $scope.obj);
}
The above code outputs into this:
My Question:
How can I properly make this work so all fields in the form are autosaved and if the page accidentally refreshes the field are populated again with the data. This is the first time I am working with session storage so Im a little confused.
Whats the most efficient way of achieving this.

You could save it as JSON data instead of doing it directly as an object.
var obj = {};
obj.name = "dooley"
obj.last = "bonheuaa"
window.sessionStorage.setItem("me", JSON.stringify( obj));
After refreshing the page you can do the following to get it back
var me = JSON.parse( window.sessionStorage.getItem("me"))
now me will have the value of the object stored.

In SessionStorage (https://developer.mozilla.org/fr/docs/Web/API/Window/sessionStorage), you can only put String object.
So, i recommend you to use Stringify on get/set of the sessionStorage.
See this post for more information.

Related

Asp.Net MVC app - caching data between page loads

I have a simple Asp.Net MVC app. I have a form, which I'm trying to gather data for, and then submit. However, within that form is a list of selections - each time a selection is made, I go to the server to add that data:
function addSelection(item) {
fetch("/test/selection/" + item,
{
method: "POST"
})
.then(response => {
const name = document.getElementById('Name').value;
localStorage.setItem("name", name);
if (response.ok) {
location.reload();
} else {
console.error("Unable to add");
}
});
}
The server then stores the list in a HttpContext.Session variable.
The target is to keep the name property in place across calls. The code above works great - I set the control on load:
window.onload = function() {
var getName = localStorage.getItem('name');
document.getElementById('Name').setAttribute('value', getName);
}
However, the form itself is eventually submitted, and the entire form, with the selected items, is submitted to the server:
<div>
<input type="submit" value="Submit"
asp-controller="My" asp-action="Create"/>
</div>
The problem that I have is that the local storage still retains the value of name, and so the next time the form is loaded, it's still there. Does anyone have any techniques for achieving the same result without using local storage?
The only solution that I can think of so far is to replace the submit button with a manually coded JS script that resets the value, but that doesn't account for situations where the user just moves away from the form. I feel like I'm heading down a rabbit hole of my own making, and there must be a simpler way to do the same thing.
One solution is to use hidden form fields to persist the data between requests instead of local storage. On each item selection, add the data to a hidden form field on the client-side instead of saving it to local storage. Then, when the form is submitted, the hidden form field value will be included in the form data and can be retrieved on the server-side.
On the server-side, you can retrieve the NameValue from the form data in your action method.
[HttpPost]
public IActionResult Create(string NameValue, ...)
{
...
}

How edit html data which is existing in localstorage?

I have set a data to the javascript localstorage, i want to edit the data, which i am passing dynamic content . my code is
$(".table tr."+data_name+"").each(function(){
countss++;
selected.push("<table class='str"+countss+"' data-name='"+data_name+"' style='width:655px;'><tbody><tr><td>"+$(this).find('td').text()+"<span><input type='number' min='100' class='productQuantity quantityUpdate"+count+"' data-name='"+data_name+"' data-count='"+count+"' value='100' style='float:right;'/></span></td></tr></tbody></table>");
});
var values = selected.join('<br>');
localStorage.setItem(data_name,values);
here i want to edit the data which is dynamic in the push data
anybody have idea to change the dynamic value ?
without extract the local storage html content?
If you still have the values you can just update it and then localStorage.setItem again. If you dont you have to do localStorage.getItem(data_name) and then update, then localStorage.setItem again
You can almost view local storage as a type of database transaction.. It wont just update because you have updated the values var you actually have to persist the value by doing setItem

Fetch localStorage values to other page using id

I am storing the values in localStorage and the values are getting stored through input[type:hidden] and input[type:text].
JS:
$('.proceed_btn').on('click', function() {
// Blank to start with
var order = {};
// Loop through all inputs...
$('input[type="text"], input[type="hidden"]').each(function() {
// ...adding their values as properties
order[this.name] = this.value;
});
// Store that object in JSON format
localStorage.setItem("order", JSON.stringify(order));
});
I want to print these value in other page when the user redirects after submitting the form. I am working on ruby currently. There are many products in the website, so the information in the summary page gets rendered according to that. Is there any way to display specific form details in through there id's?
You can create a partial with .js.erb extension eg _order_partial.js.erb and retrieve the order object as thus:
order = JSON.parse(localStorage.getItem("order"));
// Loop through the object and print out
Then you can render the partial in any of the views file you want to use it.

I am unable to retrieve localStorage data, as stored format appears different?

I am a newbie to programming, and apologies in advance if this has been answered before. I have done some searches and it doesn't look to me like this specific question has been answered.
Before attempting to store a large volume of data in localStorage (HTML5, Chrome, Windows), I have tried some sample data and attempted to store data. When I do a console display before storing the variable shows all the data correctly. I also seem to have some success because I see the sample data in the localStorage via the console.
However, I am baffled that the data appears multiple times in a continuous line. When I try to retrieve the data with a getItem, I get a null. I am not doing anything fancy for either storing or for retrieving data.
The code I use for storing and retrieving are shown below, as also the data in the localStorage as viewed by the Chrome console.
I have also tried JSONstringify in one of my attempts.
Storing:
window.localStorage.setItem('result', zlldata);
Retrieving:
GETzlldata = window.localStorage.getItem(zlldata);
zlldata = JSON.parse(GETzlldata);
Data in the LS look like this: (I tried 2 different approaches, once with 'this.zlldata' and the other time with 'result' in the setItem attempts.
this.zlldata: "undefined"
{"zipLatLong": [
{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},
{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},
{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},
{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}
]
}
{"zipLatLong": [
{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},
{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},
{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},
{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}
]
}
Question I have is how do I retrieve the data. I mentioned that data looks different because of all the 'return' characters that show up. Regardless the data should be 'retrievable'. I have allocated enough space in localStorage for the purpose at 5 MB. The format is the same for all records. The purpose of this exercise is a project that I am doing for the course and this approach has other uses. I am aware that in the real world other easier ways are available (e.g. via APIs to websites).
Appreciate any help. Just as additional info, I don;t need to retrieve all data each time, but only need to validate that the zipcode (for eg, exists)
Thanks again in advance and sorry for the lengthy post
To put complex data into localStorage:
localStrorage.setItem("name", JSON.stringify(theData));
To read complex data out of localStorage:
var theData = JSON.parse(localStorage.getItem("name") || "null");
if (theData) {
// It wasn't there, initialize it
}
(Naturally, the above only works with values that can be converted to and from JSON. If you have values that don't convert readily, like dates, you can use a replacer function with JSON.stringify and a reviver function with JSON.parse to handle them.)
Full example on jsFiddle (Stack Snippets don't allow localStorage): https://jsfiddle.net/aj2mq4rz/1
HTML:
<div>
<label>
Name:
<input type="text" id="field-name">
</label>
</div>
<div>
<label>
Age:
<input type="text" id="field-age">
</label>
</div>
<input type="button" id="btn-save" value="Save">
JavaScript:
// On page load, read our data
var theData = JSON.parse(localStorage.getItem("someName") || "null");
if (!theData) {
theData = {
name: "",
age: 0
};
}
var nameField = document.getElementById("field-name");
nameField.value = theData.name;
var ageField = document.getElementById("field-age");
ageField.value = theData.age;
document.getElementById("btn-save").onclick = function() {
// Update our object
theData.name = nameField.value;
theData.age = +ageField.value;
// And save it to local storage
localStorage.setItem("someName", JSON.stringify(theData));
}
You are using:
window.localStorage.setItem('result', zlldata); for storing but using window.localStorage.getItem(zlldata);for retrieving. You cannot retrieve with the value, you need to use the key. So, you need to use getItem('result');
I wrote a tool that will do this for you, that is, allow you to transparently set and get a javascript object (and other primitives) as a localStorage key value. (It does the conversion so you don't have to.) It's called localDataStorage.
To use it, first instantiate your storage object:
localData = localDataStorage( 'my.project' );
Then, store a key value (in this case, your object unchanged):
localData.set( 'key1', '{"zipLatLong": [{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}]}' );
Then, read it back:
x = localData.get( 'key1' );
--> "{"zipLatLong": [{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}]}"

creating a registration and login pages with localstorage

I need to create a registration and a login page with javascript and localstorage and I am very confused with a few things.
Let's say all the info that needs to be saved is a string, and I want to have an array of these strings stored locally that can grow at any time and as long as it isn't cleared it keeps growing. I need to be able to parse through that array later and compare the strings with the string that will be inputted in the login page. How do I create an array of strings in local storage and access it? I tried the following: localstorage.token = JSON.stringify(token); but then every time there's a new token it re writes it. I read a few posts but I am still a bit confused.
Thank you.
Ok, even though it's still rough at the edges, here's some proof of concept:
HTML:
<form>
<input name='abc' value='' />
<input name='def' value='' />
<input name='ghi' value='' />
<button type="button">Save</button>
</form>
JS:
$(function() {
var $form = $('form'),
$saveBtn = $('button'),
myForm = {},
myFormJsoned = localStorage.getItem('myform');
if (myFormJsoned) {
try {
myForm = JSON.parse(myFormJsoned);
$.each(myForm, function(i, obj) {
$form[0][obj.name].value = obj.value;
});
}
catch(e) {
localStorage.removeItem('myform');
}
}
$saveBtn.click(function() {
localStorage.setItem('myform',
JSON.stringify($form.serializeArray()));
});
});
The point is, when this button is clicked, the form is serialized into an array with that helping jQuery method (of course, using serialize would be even more simple - if unserialize were available). Then it's JSONed and stored into a single field of localStorage.
When you load the page, the process is reversed: JSON is parsed into Array of Objects (the result of jQuery.serializeArray), this AoO is inserted into a form back again (using convenience of $.each).
What's the concept, you may ask? My point is that it is certainly possible to work with localStorage as it were a single-string container - like cookie. But then again, I'd consider using separate container for each of the fields:
localStorage.setItem('myform_abc', $form[0].abc.value);
localStorage.setItem('myform_def', $form[0].def.value);
localStorage.setItem('myform_ghi', $form[0].ghi.value);
Well, token is a string in your case, so if you stringify it, its value will change.
You don't need to, so just do :
localStorage.token = token;
You should use JSON.stringify only for object types:
var t = {a: 5, b: 'Tom'};
// set
localStorage.special = JSON.stringify(t);
// get
var u = JSON.parse(localStorage.special);
console.log(u.a); // 5
console.log(u.b); // 'Tom'
EDIT: About your registration/login process : http://jsfiddle.net/NAzZ5/

Categories