I have fetched a list of items from web service, now i want to store the item_name on which I have clicked. I cannot store that item name, if its "bread butter" , it stores only "bread".
What shall i do now?
<script>
var sub_catidall = [];
var sub_catnameall = [];
function selected_index(sub_cat_name_all) {
alert("selected sub category" + sub_cat_name_all);
//window.localStorage.setItem("current_sub_id_all",sub_cat_id_all);
window.localStorage.setItem("DishName", sub_cat_name_all);
window.open("MenuDetails.html", "_self");
}
function jsondata(data) {
var parsedata = JSON.parse(JSON.stringify(data));
var sub_category = parsedata["Item List"];
for (var i = 0; i < sub_category.length; i++) {
var sub_menuall = sub_category[i];
sub_catidall = sub_menuall['menuItemId'];
sub_catnameall = sub_menuall['menuItemName'];
//alert(sub_catnameall);
var id = document.createElement("table");
if ((i % 2) == 0) {
id.innerHTML += '<br><td><strong><font face="DEVROYE">' + sub_menuall['menuItemName'] + '</td></strong>';
document.getElementById("block_left").appendChild(id);
} else {
id.innerHTML += '<br><tr><td><strong><font face="DEVROYE">' + sub_menuall['menuItemName'] + '</td></strong>';
document.getElementById("block_right").appendChild(id);
}
}
}
jsonp("http://remoteaddress/hotelTab/menuitem.php?callback=jsondata&mCatId=" + window.localStorage.getItem('current_id') + "&menuCategoryId=" + window.localStorage.getItem('current_sub_id'));
</script>
DOM Storage Guide
Example
var string = 'Bread Butter';
localStorage.setItem("DishName", string);
alert(localStorage.getItem('DishName'));
On jsFiddle
I use Amplifyjs store library to access local storage.
It's simple to use/understand, works really well and it's cross browser (mobile browser as well)
Hope this Helps
Related
I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.
I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you
I am using the Twitch API and am attempting to pull follower images. To do this, I have to parse my most recent followers, take the name of these followers and make a request for each to obtain their user image.
$.getJSON(streamFollowers, function(json) {
for (var i = 0; i < 5; i++) {
var followerDisplayName = json.follows[i].user.display_name;
var followerName = json.follows[i].user.name;
var followerJSON = 'https://api.twitch.tv/kraken/channels/' + followerName + '';
$.getJSON(followerJSON, function(json) {
var followerImage = json.logo;
if (followerImage === "null") {
followerImage = "null.jpg";
};
});
What I am having difficulty with is attempting to pull the "followerImage" result from the "followerJSON" parse.
Heres the code in action. http://codepen.io/anon/pen/rxEPXQ
Edit: A second parse isn't required. You can pull user images from the initial parse for usernames etc. I just didn't see see it at the time. My bad.
A users logo is null if a user doesn't have a profile picture set.
http://codepen.io/anon/pen/EPBMox?editors=1011
here it is with all your followers, you can see ones with it set work properly.
var streamFollowers = "https://api.twitch.tv/kraken/channels/tsm_dyrus/follows";
$.getJSON(streamFollowers, function(json) {
for (var i = 0; i < json.follows.length; i++) {
var followerDisplayName = json.follows[i].user.display_name;
var followerName = json.follows[i].user.name;
var followerImage = json.follows[i].user.logo;
$('#followers').append('<li><img src="' + followerImage + '"></img><br />' + followerDisplayName + '</li>');
}
});
I'm trying to get the ContentTypeId of an item in sharepoint to get the full url of the item to get the binary of it and after send it to another plateform.
So here i put this code in element.xml to get the list ID and the document ids of the items i'm selecting, after this i send them to an ASPX page in a Sharepoint Dialog to define the destination of the items and after this in the postback, stream the binary and send it to the another platform. The problem is : To get the full url of my items i need ListId, ItemId and ContentTypeId.
Because i've found a code to stream the binary here :
How to Programatically Download files from sharepoint document library
And i need the full url of my items.
Any idea?
thanks
var iddocs ='';
var listId ='';
function geturl()
{
var context = SP.ClientContext.get_current();
this.web = context.get_web();
listId = SP.ListOperation.Selection.getSelectedList();
var list = this.web.get_lists().getById(listId);
var ok = false;
try
{
if ( SP.ListOperation.Selection.getSelectedItems(context) !== false)
{
var items = SP.ListOperation.Selection.getSelectedItems(context);
var url='listId:'+listId+ ' Number of selected items: ' + items.length ;
var i = 0;
if(items.length==0)
{
}else{
while( i != items.length )
{
url += ' Doc' + i + ': ' + items[i].id;
if(i>0){iddocs += '-'};
iddocs += items[i].id;
i++;
};
ok = true;
alert(url+' Id of clicked item:'+{ItemId});
};
};
}
catch(err)
{
};
return ok;
};
function OpenDialog(pidliste) {
var options = SP.UI.$create_DialogOptions();
options.width = 600;
options.height = 600;
options.title = 'Envoyer vers Nuxeo';
options.url ='/_Layouts/SPTest.CustomMenuItem/index.aspx?click={ItemId}';
if(pidliste){options.url += '&ids='+pidliste +'-'+ iddocs;};
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
function CloseCallback(result, target) {
if (result == SP.UI.DialogResult.OK) {
}
if (result == SP.UI.DialogResult.cancel) {
SP.UI.Notify.addNotification('Opération canceled', false, '', null);
}
}
if(geturl())
{
OpenDialog(listId);
}else{
alert('Please select an item');
};
I've found the solution. In fact, items can be reached via :
{SiteUrl}+{ItemUrl}
The download function is linked in my first Post. But it doesn't work for multiple items, with this method you can only reach the properties of the item you're selecting.
You have to note that if you want to access to a SP file, you have to set your request.credential via :
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
which will take the current credential you're using.
Hope it helps.
I found a code for city,state dropdown menu. It works flawlessly, but I am implementing additional feature by adding a US State to the following code:
//countries array
var countries = Object();
countries['Africa'] = '|Algeria|Angola|Benin';
//state array
var city_states = Object();
city_states['United States'] = '|Washington DC||Alabama|Alaska';
this is an array for US Cities, but I want to add a State abbreviation like so: DC, AL, AK and so on to be sent to the menu such as this:
function setRegions()
{
for (region in countries)
document.write('<option value="' + region + '">' + region + '</option>');
}
function set_country(oRegionSel, oCountrySel, oCity_StateSel)
{
var countryArr;
oCountrySel.length = 0;
oCity_StateSel.length = 0;
var region = oRegionSel.options[oRegionSel.selectedIndex].text;
if (countries[region])
{
oCountrySel.disabled = false;
oCity_StateSel.disabled = true;
oCountrySel.options[0] = new Option('SELECT COUNTRY','');
countryArr = countries[region].split('|');
for (var i = 0; i < countryArr.length; i++)
oCountrySel.options[i + 1] = new Option(countryArr[i], countryArr[i]);
document.getElementById('txtregion').innerHTML = region;
document.getElementById('txtplacename').innerHTML = '';
}
else oCountrySel.disabled = true;
}
function set_city_state(oCountrySel, oCity_StateSel)
{
var city_stateArr;
oCity_StateSel.length = 0;
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
if (city_states[country])
{
oCity_StateSel.disabled = false;
oCity_StateSel.options[0] = new Option('SELECT NEAREST DIVISION','');
city_stateArr = city_states[country].split('|');
for (var i = 0; i < city_stateArr.length; i++)
oCity_StateSel.options[i+1] = new Option(city_stateArr[i],city_stateArr[i]);
document.getElementById('txtplacename').innerHTML = country;
}
else oCity_StateSel.disabled = true;
}
function print_city_state(oCountrySel, oCity_StateSel)
{
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
var city_state = oCity_StateSel.options[oCity_StateSel.selectedIndex].text;
if (city_state && city_states[country].indexOf(city_state) != -1)
document.getElementById('txtplacename').innerHTML = city_state + ', ' + country;
else document.getElementById('txtplacename').innerHTML = country;
}
I was thinking adding an additional array of State abbreviations, but I think adding a simple state abbreviation to the already built array would do just fine by adding another value in the setregions() and having + abbreviation + instead of + region +. Any ideas how to implement it? -thank you.
If you have an array of States (objects) rather than an array of Strings you could do something like this:
function State(longName, shortName) {
this.longName = longName;
this.shortName = shortName;
}
I don't know what the abbreviations are, but store them like this in your array
var cityStates = "State:Abbrev|Washington DC:WDC|ETC:etc"
var stateNames = cityStates.split("|");
var states = new Array(stateNames.length);
for (i=0; i<states.length; i++)
var longName = stateNames[i].split(":")[0];
var shortName = stateNames[i].split(":")[1];
states[i] = new State(longName,shortName);
}
That would give you a new array "states" with 50 state objects, each which could be called like this:
states[0] //(returns a State object at index 0)
states[0].longName //(returns the long name)
states[0].shortName //(returns the abbreviated name)