handling a cookie ( delete) - javascript

Im using chkArray.push($(this).val()); and document.cookie = 'ids='+chkArray; within a $('input[type=checkbox]:checked').each(function() to store checkboxes values. Then with a simple onclick function (AJAX) fecth products info from db and display in a div.
So far it is working well, but :
How can I reset / Delete the {name:values} created with document.cookie after the onlick event ?
I tried document.cookie.length = 0; and chkArray.length = 0; but it is not working.
How to call the Array with the ids/values ? When I use the debugging console in chrome I can see under cookies Name(ids) and values ( XXX,XXX )
If I want to store different values within the same function using document.coolie, will it replace the first pair (key:value) created from the checkboxes or added to it?
var x = 'abcd'; document.cookie = 'XName='+x;
thanks

You can reset all cookies with document.cookie = ''. You can empty an array with chkArray = []
The cookie format is a key-value pair. For example, document.cookie = 'ids=hi; name=Han'. Now you have a cookie with two key-value pairs. ids and name.
You have to loop yourself to get values out the array. You can use array.join(','). You get a comma seperated list of ids

Since you are already using jQuery, you can have a look at this plugin : jquery-cookie to help you with your problems.

Related

How to store a list into a cookie and view in another page?

How do I store this ordered list into a cookie so that I can view it in another page ? What should be the syntax of the target page ?
Coffee
Tea
Milk
Thanks
For example, you can use the jQuery.cookie plugin to manage your cookies.
var list = ['coffee', 'tea', 'milk'];
$.cookie('cookie_name', JSON.stringify(list));
To get the values and transform in an array, you have to do that:
var list = JSON.parse($.cookie('cookie_name'));
Hope it helps.
You can get and set cookie values in JavaScript with document.cookie:
document.cookie = "list=,Coffee,Tea,Milk";
Here I set the data with the key of "list". To access value you will need to parse the cookie for the key "list". Cookies only store string values so you will need to turn it into an array as well:
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)list\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var list = cookieValue.split(",");
console.log(list)

remember all values in an array using cookies - javascript

i want to be able to remember all values in an array using cookies, but do not know how. I am also using js-cookies.
Here is my code:
var usernames = new Array();
var input = $('#input').val();
usernames.push(input);
// each time something is inputted, it'll be saved to the
// array usernames. I want it so that when refreshed, all
// of the inputs remain in 'usernames'
alert(usernames);
As mentioned, localStorage is a better place to store this data, but using cookies follows the same steps, just need to get a set/get method for Cookies. First you need to see if there is a value. If there is you need to parse it. After you update the array, you need to convert the value to a string and store it.
//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];
//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);
//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());

Get ID by key in localStorage

In JS localStorage I can use
localStorage.getItem(key);
to get the value of the entry corresponding to the key in the key variable.
How can I get the entry's ID (instead of value) using the key?
Edit: sorry I must have confused people. What I mean by "key" is the numerical key - which is 0, 1, 2, 3 etc depending on how many items have been saved. Then I want to find out the ID it was stored as, eg foo in the below example, from the numerical key.
localStorage.setItem('foo', 'bar');
LocalStorage is implemented as a key-value pair ( see for instance: https://developers.google.com/web-toolkit/doc/latest/DevGuideHtml5Storage ) - so you don't have an id like an unique auto-incremented id in a database table.
However, you can access the elements using an index - to get the index of a key in localStorage, the only way I can find is to loop through each key until you find the one you are searching for, like this:
var findIndexOfKey = function(searchKey) {
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
if(key === searchKey)
return i;
}
return -1;
}
And then, to retrieve the key using the index, you can do:
localStorage.key(myIndex);
And to retrieve the value, you can do this:
localStorage.getItem(localStorage.key(myIndex));
... or this ( which would be equivalent to localStorage.getItem("myKey")):
localStorage.getItem(localStorage.key(findIndexOfKey("myKey")));
when setting the item you should give it's ID as a value and than when you call getItem(key) it should give it's ID as a return ex:
localStorage.setItem('foo', 'bar');
localStorage.getItem('foo'); // it should return the bar
take a look for this examples it may help : http://mathiasbynens.be/notes/localstorage-pattern
The answer:
localStorage.key(key);
Sorry, I realise I've got confused between what's actually called the key, which I called the ID, and it's numerical ID which I called the key...
I don't think it is possible. Can't you just make localStorage.setItem(yourkey,value)? I mean
localStorage.setItem(0,value)
localStorage.setItem(1,value)
This may be useful in loops for example.

TaffyDB: Select problems

I'm new to TaffyDB and haven't done a lot of javascript programming so I'm hoping that the problem I'm having is something simple. I'm trying to update a listbox with the options stored in the TaffyDB according to the selected client. When I do my select however, it is returning all the rows.
Below is the code I am using to update the listbox, along with the selectString used to do the query, and what's in the TaffyDB.
Anyone have any ideas why I am getting back all rows when I specify clientID = 1788?
I tried the select string with and without quotes around the column identifier.
// load existing user client projects if we have any
var lbProjects = document.getElementById('lbProjects');
lbProjects.options.length = 0;
var selectString = '{clientID:"' + clientID + '"}';
alert(selectString);
userProjects(selectString).each(
function (r) {
var option = new Option();
option.value = r.projectID;
option.text = r.projectName;
lbProjects.add(option, null);
});
What's in selectString:
{clientID:"1788"}
What's in the DB:
[{"clientID":"1788","projectID":"19"},
{"clientID":"1789","projectID":"24"},
{"clientID":"1790","projectID":"23"}]
Thanks for any help.
Aaron L. Bratcher
The problem was trying to use the selectString variable.
The line
userProjects(selectString).each(
now reads
userProjects({clientID: clientIDValue}).each(
I was supposed to be passing in an object array, not a string. {} in javascript creates an array of objects.

How to set certain element values to null in JavaSctipt

I have some items I am storing in an element that get added at various times like this:
document.getElementById('rout_markers').value = str;
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
How can I do that?
Thanks!
If you're assigning str to an element then there are no arrays involved here - you'll be overwriting each previously-assigned value with the latest and thereby storing only the latest value.
You could use an array but you'd have to know the location of each item in the array, so if you wanted to assign or nullify a specific element in your array, you'd have to a have a record of where it was - although you could get around that it with a multi-dimensioned array, where the first element at each index is the name of the property, and the second element at each index is that value of the property.
If you want to store multiple properties in a field in order to retrieve them all later, there are two simple ways of doing this.
Consider using either a field for every property.
If you do this then I'd suggest using a naming convention for the fields so that you can more easily assign the property.
Concatenating a string to form a collection of key-value pairs, very much like a query-string.
In the example you gave, this would mean storing something like:
var keyVals = 'route_markers' + '=' + str + '&';
document.getElementById('myHiddenProperties').value = keyVals;
When you want to assign another property to this string you do something like this:
keyVals = document.getElementById('myHiddenProperties').value;
keyVals += 'new_property' + '=' + myNewValue + '&';
document.getElementById('myHiddenProperties').value = keyVals;
In this way, if you want to remove a specific key-value pair, you split the stored value like this
var arrKeyVals = document.getElementById('myHiddenProperties').value.split('&');
You then have an array of key-value pairs.
If you want to retrieve a value from this array, or blank one of the values then loop through this array, splitting each into its key and value, like this:
for (var i = 0; i < arrKeyVals.length; i++) {
var keyVal = arrKeyVals[i].split('=');
var key = keyVal[0];
var val = keyVal[1];
if (key == name_of_key_sought) {
val = ''; //assign an empty string to this property to forget about it
}
}
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
No, the value property of certain HTML elements is just a string value. (And it only exists on certain elements, like input.) Assigning a new value to value will overwrite the previous value, not store it in an array.
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
This part of the question sort of goes away because of the answer to the first part, but you can clear the value property by assigning an empty string to it.
If by any chance you mean remove/hide the element itself (the text box) then you can have such code:
document.getElementById('rout_markers').style.display = 'none';
Otherwise the other answers here cover it all nicely.

Categories

Resources