JavaScript list saving question - javascript

I have this fiddle: http://jsfiddle.net/y8Uju/5/
I am trying to save the numbers, because, when I submit, the list of numbers gets erased. I am a little new to JavaScript so am not quite familiar to what is available. In PHP I would use sessions to save the list, but what can I do in JavaScript to do this?
Here is the JavaScript code:
function bindName() {
var inputNames = document.getElementById("names").getElementsByTagName("input");
for (i = 0; i < inputNames.length; i++) {
inputNames[i].onkeydown = function() {
if (this.value == "") {
setTimeout(deletename(this), 1000);
}
}
}
}
document.getElementById("addName").onclick = function() {
var num1 = document.getElementById("name");
var myRegEx = /^[0-9]{10}$/;
var itemsToTest = num1.value;
if (myRegEx.test(itemsToTest)) {
var form1 = document.getElementById("names");
var nameOfnames = form1.getElementsByClassName("inputNames").length;
var newGuy1 = document.createElement("input");
newGuy1.setAttribute("class", "inputNames");
newGuy1.setAttribute("id", nameOfnames);
newGuy1.setAttribute("type", "text");
newGuy1.setAttribute("value", num1.value);
form1.appendChild(newGuy1);
num1.value = "";
bindName();
}
else {
alert('error');
}
};
function deletename(name) {
if (name.value == "") {
document.getElementById("names").removeChild(name);
}
}

You can use localStorage: http://jsfiddle.net/y8Uju/8/
Loading:
var saved = JSON.parse(localStorage["numbers"] || "[]");
for(var i = 0; i < saved.length; i++) {
document.getElementById("name").value = saved[i];
add(false);
}
Saving:
var saved = JSON.parse(localStorage["numbers"] || "[]");
saved.push(num1.value);
localStorage["numbers"] = JSON.stringify(saved);
And define the function of the addName button separately, so that you can call it when loading as well.
Edit: You have to execute a function when the page is loading to fetch the stored numbers, and add some code to save the entered number when one clicks the Add button.
For storing you can use localStorage, but this only accepts Strings. To convert an array (an array containing the entered numbers), you can use JSON.
When loading, you need to add the numbers just like happens when the user fills them in. So you can set the name input box value to the saved number for each element in the array, and then simulate a click on the Add button.
So you need an add function that is executed when:
User clicks Add button
Page is loaded
However, when simulating the click the numbers should not get stored again. You need to distinguish between a real click and a simulated one. You can accomplish this by adding an argument to the add function which represents whether or not to store.

Not entirely sure what the question is, but one problem I see with the code - id's can't be numbers, or start with numbers
var nameOfnames = form1.getElementsByClassName("inputNames").length;
//....
newGuy1.setAttribute("id", nameOfnames);
That might be slowing you down somewhat. Perhaps set id to 'newguy' + nameOfnames

Jeff, the reason that the page keeps getting erased is because the form submission triggers a page reload. You need to place a listener on the form submit event and then send the data through AJAX. This way the data is POSTed to "text.php" without reloading the page with the form.
You could place the values in a cookie but that is not ideal because you have a fairly limited amount of space to work with (4kb). I also get the feeling that you're trying to hand them off to some server side script so HTML5 local storge wouldnt be a good solution, not to mention that your eliminating over half of the people on the internet from using your site that way.
Since browsers are inconsistent in how they attach event listeners AND how they make AJAX requests. I think that most people would recommend that you use a library like jQuery, dojo, or prototype which abstract the process into one function that works in all browsers. (my personal fav is jQuery)

There are a few options available to you:
Save it client side using cookies (http://www.quirksmode.org/js/cookies.html)
Save it client side using HTML5 local storage (http://diveintohtml5.ep.io/storage.html)
Save it server-side using Ajax
The Ajax solution involves a server side page (in PHP for example) that reads a request (a POST request for example) and saves it into a database or other. You then query that page in JavaScript using XmlHTTPRequest or your favorite library.

Related

how to save state of the page when refreshing? (HTML, JS)

(DISCLAIMER: I'm new to coding so my code probably isn't optimal. If you know a better way to do it, feel free to leave it in the comments )
Most of the time I had no idea what I was doing, but with patience and with you guys' help I came up with this:
if (window.localStorage) {
// Create the Key/Value
var cNum = localStorage.getItem("currentNumber");
if (localStorage.currentNumber == undefined) {
localStorage.setItem("currentNumber","0");}
// Variables
resetCount.innerHTML = localStorage.currentNumber;
// Functions
function btnR() {
cNum++;
localStorage.currentNumber = cNum;
resetCount.innerHTML = cNum;}}
else { console.log("No"); }
HTML:
<button id="resetButton" onclick="btnR()">Reset</button>
<p id="resetCount">0</p>
I was creating a button that each time you click on it, it reset the checkboxes, but I also wanted a counter to see how many times they got rested. The problem was that every time I click the button the counter also reset. Now that is solved I can try to apply the same thing for the checkboxes, so they don't reset on refresh either.
Note: I had to put the .SetItem in an if statement cause, even tho the value was in storage it kept setting back the value to zero every time I refreshed the page. This was the way I found to stop that.
You either need to set up a back end to send data to and save the information you want to keep stored, or save data in localStorage.
Just know it is not the best practice to save sensitive info in localStorage (as they can be compromised in cross-site scripting attacks).
localStorage.setItem puts a bit of data into localStorage (and that stays there till you clear it) and localStorage.getData extracts it.
This might help get you started on localStorage, but you will have to figure out the function to set the colour to the element you have.
let boxColour = localStorage.getItem("boxColour");
if (boxColour === null) {
setBoxColour("colour");
} else {
setBoxColour(boxColour);
}
function setBoxColour(colour){ localStorage.setItem("colour");}
/* Inside the function you have to get the item and change it's style attribute or add a class to add styles */
Careful with that localStorage data!
You could use LocalStorage.
It saves data in the page to be used after when the page is refreshed or closed and opened later.
Theres a example:
(Unfortunally, it seems to not work in the stackoverflow site, but if you try at your HTML file it will work)
var loadFunc = (elem) => {
console.log("Value saved is: "+ localStorage.getItem("savedValue"));
if(localStorage.getItem("savedValue")){ //checks if value is saved or not
elem.checked = localStorage.getItem("savedValue");
}
}
var clickFunc = (elem) => {
localStorage.setItem("savedValue", elem.checked); //set te value if in localStorage
}
Click the checkbox and the value will be saved.
<input type="checkbox" onload="loadFunc(this)" onclick="clickFunc(this)">

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

share variable among pages

I have a simple JavaScript file which takes care of the translation on the page. So if user wants to see a page in e.g. English, he clicks on it and the page translates itself. Everything works great except when user goes to another page.
Now my JavaScript is re-loaded again, and default language kicks in. Which is undesirable - I want my JavaScript to remember what language user has specified.
Here is my JavaScript code to show what I am doing
//translations
var language = "en";
$(function () {
translatePage();
$("#PageLanguages li").on("click", function (attr) {
var selLang = $(this).data("language");
if (selLang) {
language = selLang;
}
translatePage();
});
function translatePage() {
$.ajax({
url: 'languages.xml',
success: function (xml) {
$(xml).find('translation').each(function () {
var id = $(this).attr('id');
var text = $(this).find(language).text();
$("#" + id).text(text);
});
},
error: function (err) {
var x = err;
}
});
};
});
As you can see, I am storing language (the one user has specified) in my language variable at the top.
What do I need to do, when I would like to website to share a variable among all pages (such as in this case) ?
My advice here is browser based , using local storage with the modern browsers
localStorage.setItem('language', 'eng');
// Retrieve the object from storage
var retrievedLanguage = localStorage.getItem('language');
console.log(retrievedLanguage); /// prints eng
If target browsers are html5 compliant , try local storage :
//set data
localStorage.setItem("language", language);
// get data
var language = localStorage.getItem("language");
will be available for all pages.
There are several ways you can go about doing this. But I'll list just three. If you want the JavaScript approach (which relies on JavaScript being enabled/supported by the browser):
var language = localStorage.getItem("language") || "";
if(language !== "")
{
// Set the language for content in here
}
else
{
// Store the language in LocalStorage here.
localStorage.setItem("language", "en-us");
}
Alternatively, you could store stuff like this in your Database (server-side), but I would advise against storing such things in your own database unless you absolutely need to ensure that value will exist when you need it.
Another option is appending something like language=en-us to your query string when they click on a hyperlink or button. And you could then use JavaScript or a server-side language on the next page to get this data from the query string.
There is different way to keep the language variable in all pages.
1) Use the language string in URL itself ex :
https://www.paypal.com/ar/webapps/mpp/home
2) Call server to know the language.
3) Store in cookie as specified by uzaif
4) Using localStorage

Loading div object from DoM. Convert to Text File. Then reload div object back when page is reloaded

I have a co worker who asked me for help but I wasn't able to. Essentially he has created a page with pure java script that has a div element and child div elements. Each one of those child div elements have a form. He wants to be able to save all that hierarchical data in a text file whether or not it is in json / html in which he can load it later on without having to process it manually again. That way the next time the person loads the page, they are greeted with all the same information and div elements.
So essentially when you load the page again, you are able to simply dump the json / html into the DoM and it will automagically work. He's been on it for 2 days now, I thought I would ask you guys for some help or at least lead me on the right path.
Doing so would take three steps:
Get all the form data values from the DOM (a simple matter of knowing how to access HTML forms and putting them into an object)
Save the form data object into localStorage or on server (saving on the server would only work if you save some identifying information about the user, like if they are logged in, or their IP address)
On form load, check for saved data (on localStorage or server) and load it into the forms.
You can get the data of all forms into a JSON object like so:
function getAllFormsData(){
var formsData = {}
for(var i=0;i<document.forms.length;i++){
var form = document.forms[i],
name = document.forms[i].name;
formsData[name] = {}
for(var j=0;j<form.elements.length;j++){
var element = form.elements[j];
if(element.type=="submit") continue;
formsData[name][element.name] = element.value;
}
}
return formsData;
}
so formsData is a JSON object that contains properties for each form (by its name, but you can use ID if you prefer) on the page, and the value of each of those properties is an object containing the name and value of each input element (unless it's a submit type element).
Saving the data can be triggered either by the user clicking a "Save" Button on the page, or by using the window.onunload event. (If you are using localStorage, you can also set the saving function inside a setInterval that triggers every 30 seconds or whatever.)
localStorage is pretty straightforward (with a really easy API), but only allows string values. If you want to load a whole object into it instead of having to loop through and save each value, you can use a library. I have found store.js to be very useful and straightforward, and it serializes data for you so you don't need to mess with JSON.parse or JSON.stringify.
So, using the library, the save function would boil down to something as simple as:
function saveAllFormsData(){
var data = getAllFormsData();
for(var formName in data)
store.set(formName, data[formName]);
}
And on load, you can call this function:
function restoreAllFormsData(){
var forms = document.forms;
for(var i=0;i<forms.length;i++){
var form = forms[i];
if(store.get(form.name)){
for(var j=0;j<form.elements.length;j++){
var element = form.elements[j];
if(element.type=="submit")
continue;
element.value = store.get(form.name)[element.name];
}
}
}
}
I suggest looking into HTML5 local storage. This will allow you to save form data on the client, which can be used for repopulation when necessary.
Alternatively, you could also set a cookie on the client. However, this method has drawbacks that are discussed in the aforementioned document.
Either approach will likely require you to stringify any HTML before storage, due to the key:value nature of these data storage methods.

Form - update "reset" button to new data

I'm using mootools in 1 of my projects. I'm working on easy to be customised menu based on sortables.
So here's the issue - I've got the form which contains menu node informations. Form is updated with JS whenever user chooses different node (form is populated with new data). Problem is that "reset" button obviously "remembers" the initial data, so whenever user clicks it, it loads initial data form.
Is there anyway to update the "default" form status, whenever i load new data? (ofc i could write piece of code which do whatever i need, but if there is some simplier solution which allows default "reset" button to work with new data would be much less work to use it :))
Thanks in advance for help
i cant think of anything else except getting a new source through ajax with data prepopulated and replace the innerhtml hence replacing the form itself.
you can use something like toQueryString to serialize the form and then reverse it based upon the mootools-more's String.parseQueryString():
(function() {
Element.implement({
saveFormState: function() {
if (this.get('tag') !== 'form')
return;
this.store("defaults", this.toQueryString());
},
restoreFormState: function() {
if (this.get('tag') !== 'form')
return;
var vals = this.retrieve("defaults");
if (!vals.length)
return;
var self = this;
Object.each(vals.parseQueryString(vals), function(value, key) {
var el = self.getElement("[name=" + key + "]");
el && el.set('value', value);
});
}
});
})();
var f = document.id('f');
// save default
f.saveFormState();
document.getElement("button").addEvent("click", f.restoreFormState.bind(f));
this ough to cover most cases and you can always save a new defaults state. need to test it somewhat with radios and suchlike, though.
here's a basic fiddle with a save/restore: http://jsfiddle.net/UWTUJ/1/
relevant docs: http://mootools.net/docs/more/Types/String.QueryString (more) and http://mootools.net/docs/core/Element/Element#Element:toQueryString (core)
implied reliance on name attributes on all form elements you want to save/restore.
I have previously created more complex save/restore states that even return field CSS class names, validation messages, etc.

Categories

Resources