Working with cookies in javascript - javascript

For an assignment I had a few weeks ago we were asked to create two divs, one which collects and saves diary entries and one which displays the diary entries. We were asked to use the HTML form element and this should be proccessed using JS. Since it wasn't a server-side assignment were were asked to store the submitted diary entries using cookies I didn't get the assignment out and since the lecturer never posted the solution or went through a solution I was wondering if someone would be able to look at mine and show me how to do it. I was unsure how to actually set the cookie and return it. I'll also post a link to the js fiddle if that helps anyone.
So in short, I want to be able to save the values of the input box one the save entry button is clicked, and show this value once show diary is clicked
Thanks in advance
HTML
<form name ="name" onsubmit="return doSomething();">
Please Enter Your Diary Entry: <input type="text" name=“somename” id="frm_somename"/>
<input type="submit" name="Submit" value="Save Entry" />
</form>
<div id = "1">
<button id="button" onclick="y();">Show Diary</button>
</div>
JS
doSomething = function() {
// get the data from the form
var textValue = document.getElementById("frm_somename").value;
// the rest of the code goes here
// return false to stop form going somewhere - NB
return false;
}
Here's the link for the js fiddle also if that's any help https://jsfiddle.net/jon123/m957kc84/

You can do this pretty easily using just vanilla javascript... JavaScript can create, read, and delete cookies with the document.cookie property. This resource should answer all of your questions.
Also you are going to need to rewrite your JS... currently you dont have an appropriate click handler function created among some other issues.

You can achieve this in Javascript in two ways:-
Using Cookies
To simplify your work with cookies, you can use the js-cookie library. So, adding data to cookie can be easily achieved as follows:-
Cookies.set('diaryEntry1', 'This is a test diary entry.');
//In order to get the values stored in a cookie, you can do this-
Cookies.get('diaryEntry1');
When creating a cookie you can also pass an Array or Object Literal instead of a string in the value. If you do so, js-cookie will store the string representation of the object according to JSON.stringify:
Cookies.set('diaryEntries', { entry1: 'Diary entry 1', entry2: 'Diary entry 2' });
//When you will try to get this, it will return a string representation of the object.
Cookies.get('diaryEntries'); // => '{"entry1":"Diary entry 1", "entry2":"Diary entry 2"}'
Using localStorage
Local storage is a part of web storage, which itself is part of the HTML5 specification. In simple terms, all that localStorage does is store named key/value pairs locally and unlike cookies this data persists even if you close your browser or turn off your computer.
window.localStorage.setItem('diaryEntry1', 'This is a test diary entry.'');
window.localStorage.getItem('diaryEntry1');
The support for localStorage is pretty good for an HTML5 specification; it is supported by all the major browsers and even IE8, so the only thing you might need to be wary of is IE7 if you’re still supporting that.
In my opinion, you should go for localStorage since my guess would be that you would like to keep the data even after the user closes the browser. Hope this helps!

Related

How can I store a JavaScript variable in local storage?

So I have a JavaScript variable called addNumber which just adds a number by 1 to a div any time I click a button. But I'm using it on a website which has multiple pages, and every time I change pages, it resets the counter. I've used console.log() to check the variable multiple times, and it always resets back to zero any time I leave the page, even when I keep the tab open. This counter is kept at the top of the page for all to see, and I want it kept there in a navbar, kind of like the shopping cart on Amazon. Is there a way I can do something like that using only vanilla JavaScript?
Thank you.
You may find this link helpfull.
https://www.w3schools.com/jsref/prop_win_localstorage.asp
Quick answer you store key value pairs using a string tag to identify them:
localStorage.setItem("lastname", "Smith");
localStorage.getItem("lastname"); //this returns the string "Smith"
Edit: i do not recommend you doing this in a production enviroment. You should stick to the framework of the project. If the project has no framework or is just for school or learning purposes then i guess is a viable option.
You can store a variable in localStorage to access it somewhere else through
Try using:
function onClickevent(){
addNumber = addNumber +1
localStorage.setItem('counter', addNumber);
}
Then get it through
//Just assign it to your div
const getIt = localStorage.getItem('counter')
Here is some documentation on LocalStorage and how to use it :)
https://www.w3schools.com/jsref/met_storage_getitem.asp
https://blog.logrocket.com/localstorage-javascript-complete-guide/#:~:text=To%20get%20items%20from%20localStorage%2C%20use%20the%20getItem()%20method,in%20the%20browser's%20localStorage%20object.
The solution you can try is :
In the .js file at the end of all lines, type
window.localstorage.setItem("addNumber",addNumber);
The addNumber will be stored with an ID of addNumber.
To later retrieve, use :
window.localstorage.getItem("addNumber");
You may assign the above to a variable like
var number =....
Then console the number.
I hope this helps.

activating checkbox on load with javascript or jQuery

hello I have a small project I'm working on.
the project is calling an API with ajax and getting info about currencies, one of the things I'm stuck on is that I have to write them in cards that include a checkbox that has to stay activated after I refresh the page.
any suggestions?.. please I'm desperate
When you make your call on your API just set the checked value on the correct checkbox, please have in mind that setting checked=false will still give you a checked checkbox.
<input type="checkbox" checked>
One way to preserve information against a page refresh is to use localStorage.
LocalStorage allows you to store key:value variable pairs in the local browser. You can view the localStorage values for any given website in DevTools F12, on the Application tab. The variables are stored by website, and remain as they are until (a) they are deleted, or (b) browser cache is cleared. (For more info on when localStorage is cleared, see this answer).
LocalStorage is dead-simple to use:
let myPet = 'Cat';
localStorage.setItem('animal', myPet);
And to read it:
let myPet = localStorage.getItem('animal');
What you might want to do in your project, perhaps on a timer - or after the ajax call - is loop through your fields and create an object with all the fieldnames/values. Then use JSON.stringify to turn the object into text that you can store in a localStorage variable.
Note that you will need to write something that on page load ( $(document).ready() ) will see if the fields are empty and if there is a RECENT localStorage variable (so, you might want to create second localStorage variable (you can have MANY) that has the last-updated datetime) then you read the JSON string into a javascript object and populate your field values.
I would recommend using a dictionary, putting something unique like an ID of those currencies that are checked at that time.
If the new answer you get has the same currencies as before plus more, you can use that dictionary in memory to check those items again. If you don't get the previous response, you can just add those new items to avoid unchecking the checked currencies.
Exmaple:
var dictionary = {};
// here you should do a forEach in currently checked currencies
...
dictionary[id] = value; // (true, because it is the value of checked)
Hope it helps you.

Manipulaitng javascript cookie on blur , focus ,onload and tabclose?

I will try to be as clear as possible.
Ok.I am making a simple tracker where it becomes very important for me to track user behaviour .I am using a javascript cookie for this purpose.
what I do :
After tracking the user,I get some data which I store in a javascript object literal.
var object = {
home-page :0-30,
brand-page:0-90,
mark-page :0-20,
home-page :0-10
}
I JSON.stringify the object to store the object value in a cookie.
MyQuestion :
Considering that there are two tabs opened and that I write some data in my cookie on second tab...would I get that latest data on window.focus of first tab if i read the same cookie?
Now when I come on the first tab,I want to update a property of my object(for example..home-page:0-30 is to be updated ),without altering
its order and updating the wrong property.
Can anybody guide me on this?
First you json is incorrect, it should contain only one unique id
var object = {'home-page' :'0-30', 'brand-page': '0-90', 'mark-page' : '0-20'}
Answer to you first question, yes you will get the updated data from second tab if both the tab have same domain.
Second Question: Yes you can update the same cookie and update the user info in same cookie.
You can check the steps at http://jsfiddle.net/raunakkathuria/fhe27/2/

Other separators I want use (not & and =) when I submitting a form

I have the server programmed in Cherrypy and I use also Mako Template.
And I have the variable dict (variable Mako that contain information's work) for working with the user( this I have to use Mako and JAvascript).
I have one problem that I can not pass the value's Mako to Javascript.
MAKO --->>> JAVASCRIPT and vicecersa Not can to pass.
When the user wants change the information, I need to use the form.
The information is for example the data is the identifying a person.
When I connect when the server localhost:8100 and I have in automatically dict on Url.
The user pushes the button's send.(submit) in case of change.
The server receipt the value in Javascript with the separator in Js and the old in MAko.
I have the problem for read and to convert the separator in Javascript.
It possible to change the string's submit's form While or before to sending?
I want to program the submit's form because I want to use the other delimiter(not & and =).
This is possible?
Now I write one example:
www.theuser.com/?Name=IBM&surname=PC
With if the function programmable while sending
www.thepc.com/?Name%24+IBM+%23%+Surname%24+PC
Repeat: when I sent the parameter, I not want this separator & or = and I want to use the others.
Separator
javascript Mako
= %24+
& +%23+
This Query String is the original for the my project:
http://localhost:8100/index2?json_data=demo_title%24+Demo+title+%23+proc1_script%24+script.sh+parameters+%23+proc1_chk_make%24+on+%23+outputp2_value%24++%23+demo_input_description%24+hola+mundo+%23+outputp4_visible%24+on+%23+outputp4_info%24++%23+inputdata1_max_pixels%24+1024000+%23+tag%24++%23+outputp1_id%24+nanana+%23+proc1_src_compresion%24+zip+%23+proc1_chk_cmake%24+off+%23+outputp3_description%24++%23+outputp3_value%24++%23+inputdata1_description%24+input+data+description+%23+inputp2_description%24+bien%3F+%23+inputp3_description%24+funciona+%23+proc1_cmake%24+-D+CMAKE_BUILD_TYPE%3Astring%3DRelease++%23+outputp2_visible%24+on+%23+outputp3_visible%24+on+%23+outputp1_type%24+header+%23+inputp1_type%24+text+%23+demo_params_description%24+va+bien+%23+outputp1_description%24++%23+inputdata1_type%24+image2d+%23+proc1_chk_script%24+off+%23+demo_result_description%24+win%3F+%23+outputp2_id%24+nanfdsvfa+%23+inputp1_description%24+funciona+%23+demo_wait_description%24+boh+%23+outputp4_description%24++%23+inputp2_type%24+integer+%23+inputp2_id%24+papapa+%23+outputp1_value%24++%23+outputp3_id%24+nananartrtrt+%23+inputp3_id%24+pepepe+%23+outputp3_type%24+header+%23+inputp3_visible%24++off+%23+outputp1_visible%24+on+%23+inputdata1_id%24+id_lsd+%23+outputp4_value%24++%23+inputp2_visible%24+on+%23+proc1_source%24+lsd-1.5.zip+%23+inputp3_value%24+si+%23+proc1_make%24+-j4+-C++%23+images_config_file%24+cfgmydemo.cfg+%23+outputp2_type%24+header+%23+proc1_subdir%24+xxx-1.5+%23+proc1_url%24+http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...+%23+inputdata1_image_depth%24+1x8i+%23+inputp1_id%24+popopo+%23+inputp1_value%24+si+%23+inputp2_value%24+no+%23+demo_data_filename%24+data_saved.cfg+%23+inputdata1_info%24+info_lsd+%23+outputp3_info%24++%23+inputdata1_image_format%24+.pgm+%23+outputp1_info%24++%23+inputdata1_compress%24+False+%23+inputp1_visible%24+on+%23+proc1_id%24+lsd+%23+outputp4_id%24+nana+%23+outputp2_description%24++%23+outputp4_type%24+header+%23+outputp2_info%24++%23+inputp3_type%24+float+%23+&tag=&inputp4_id=hi&inputp4_type=text&inputp4_description=hello+program&inputp4_value=no&inputp4_info=bol&inputp4_visible=on
For the moderator:
I read on the post https://stackoverflow.com/questions/13353539/how-to-change-how-the-url-is-encoded-when-a-form-is-submitted
But this was not interested in me.
P.s. The solution in Jquery or Javascript is equal for me.
Well I'm pretty sure your reasons for doing this don't justify doing it, but to answer the question, this is how you would change the tokens. I'm assuming jQuery, it's not entirely necessary but makes the code shorter.
HTML:
<form id="myform" action="myparser.php">
<input ...>
</form>
JavaScript:
$('#myform').submit(function(e){
e.preventDefault();
var q=$(this).attr('action'),f=this.elements,i;
for(i=0;i<f.length;++i){
q+=(i===0?'?':'+%23%+')+f[i].name+'%24'+f[i].value;
}
document.location.href=q;
return false;
});
That's slightly minified, so here's the gist. We begin by binding to the submit event, which we prevent (preventDefault and return false to be doubly sure), then get all the form's elements (this.elements) and iterate through them. By the end of the loop, q is a full URL which we want to submit to (using the action property and filling in all the names/values), so we just set the HREF to it and off we go. In this case to myparser.php.
Note that this does no character substitution whatsoever. You should make f[i].value safe in some way. From your question, it seems obvious that you don't want standard URL encoding, but you will need to do something to prevent bad characters being used.
Finally, this is just the sending side. You'll still need to do something clever on your server-side to actually read these values.

Get Titanium.App.Properties in another win or make it global available

Please don’t answer this if you don’t take the time to understand my question or have a reasonable answer. I have got a few answers that is far on the side and I think I explain my problem very clear. Shall this problem drive me nuts or is there somebody out there with a straight and clear answer on Titanium.App.Properties?
I have a login form that stores the username in one:
Titanium.App.Properties.setString("userName",e.value);
and the password in another:
Titanium.App.Properties.setString("passWord",e.value);
The forms TextFields holds these values(after a store) even if I close the window, shut down and restarts the app. This because of the App.Properties.getString("value"); I suppose….?!
But when I copy the hole form with its App.Properties.getString("value"); to another window, the TextFields are empty and contains no value at all. I understand that the Properties string must be there some where in App.Properties, but how can grab it and use it another place in the app?
My question is: How to get the value from my
var userNameValue = Titanium.App.Properties.getString("userNameValue");
to be available in another window or for the hole app(global)? How can I grab it and make use of it a another place in the app? I don’t see a good reason to make these, only separate words, into objects(JSON) since the userName only contains a e-mail address and the passWord consist only of continuing letters or numbers. But if you mean I have too, -how do I set this from my TextField and get it in another TextField somewhere else in my app. I have not had any luck so far. I hope you can help me out and I can keep sane.
Titanium.App.Properties.getString("userNameValue");
This is globally Available, any Propertie of the Titanium Object is accessible in each file.
but if for some reason this doesnt work for you and you want to set a global variable,
you could do the following:
Create a file called myGlobals.js //or anything else,
//Put this in there e.g
var myProperties = {};
in any file you want to use it write in the first line
Ti.include('myGlobals.js');
Then you can make a propertie global available, for example write this in app.js somewhere where the app initializes
myProperties.Username = Titanium.App.Properties.getString("userName");
Then you can get the value in each file by accesing the propertie
myProperties.Username
//of course the Propertie has to be set before you can get them
( Titanium.App.Properties.setString("userName",e.value); ) //like you do it
But, Titanium.App.Properties.getString("userName");
should be avilable from any file anyway, (but you can give this a try although i dont think its nice to do it like this)
i had a similar problem where this didnt get any value from a propertie set in the ios settings as default value.
I had to go to the settings and manually change or edit the default value and then after a restart
Titanium.App.Properties.getString("userName");
returned the value as it should,
i hope this helps you =)
Answer to the Comment
I'm glad i could help you =)
Yes you can Use an focus EventHandler like this :
textfield.addEventListener("focus",function(){
textfield.value = "Test";
});
Beside that , are you using the identical Textfield for both windows ? like
var Textfield = Ti.Ui.createTextField({...});
and add it to 2 different windows ?
win1.add(Textfield);
win2.add(Textfield);
That led for me to Problems with labels in TableViewRows, using an identical Row 2 times in the TableView
The Text displayed only on 1 Label, sometimes it switched the Labels
I think you can't add one and the same titanium object to more then one other object
Maybe that could be the culprit,
dunno just an idea =)

Categories