JavaScript - Any Way To Store An Object In Localstorage?
Hi all,
I've been experimenting with Local Storage. I can do things like this just fine: localStorage.setItem('variable_name', variable_value); // write a value var variable_value = localStorage.getItem('variable_name'); // read a value localStorage.removeItem('variable_name'); // delete a value But if I do this: var object = { width : w, height : h }; ...then place it in local storage, reading it back gives me a TEXT STRING that says "[Object object]" and not the actual object. I would like to be able to store multiple values in one object, but it doesn't seem to work. I also tried to store a variable obtained with "document.getElementById" and when read back it just says [HTMLDivElement] (something like that) instead of the actual element. Am I doing something wrong, or does local storage not support objects? (btw, tested on FF 3.6). Thanks! -- Roger Similar TutorialsHello, I apologize if this is not in the right forum as part of my question may not be reated to javascript but I have the following problem(s). I am attempting to make a website that has three pages: index.html customize.html home.html The index page needs to have an onLoad script that does several things: 1. Checks whether the browser supports localStorage and branches to either LSYes() or LSNo() accordingly 2. LSYes has to check whether a value of NY=True or NY=False has been set in local storage. If neither has been set it redirects to customize.html, otherwise it redirects to home.html. 3. LSNo has to perform a similar check and redirect as LSYes by checking for a cookie containing the appropriate value. The customize page has to have an onLoad script that detects whether localStorage is supported and somehow be able to pass that value to another script that is called later on from a form on the page. It also has to have another script that is called from rhe form that can handle any/all of the following conditions: 1. Checking a zipcode entered in the form against a list of NY zipcodes to determine whether the person lives in NY. 2. Save the value of NY=True if it finds a match or NY=False if it doesn't in either localStorage or a cookie based on the results of the onLoad script. 3. Allow the user to clear any values that may be saved and save new values if the user moves in or out of NY. The home page needs to likewise detect whether localStorage is supported. If localStorage is not detected it has to: 1. Check for either NY=True or NY=False in the cookie 2. Change the expiration date on the cookie to one year from the current date even if the cookie has not expired. 3. Completely hide certain sections of the page if it detects a value of NY=false or if a person navigates to the page without NY value being set but show them if NY is set to true. If localStorage is detected it has to perform similar functions using localStorage. In each case, if the browser supports localStorage that is to be used instead of a cookie. There are several things this site needs to do that are beyond my current skill levels. 1. localStorage detection 2. Comparing a zipcode entered on the form to a list of NY zipcodes without making the script huge and slowing down page loading. 3. Automatically changing from index to either home or customize based on whether localStorage has been set for the site. 4. Hiding or showing sections of a page based on a value in localStorage. I have an idea how to do some of this with a cookie but when I try it it acts like no cookie is present even though I know it is so I am not sure what I am doing wrong there. I have been trying to teach myself by putting parts of various scripts that each perform part of what I need together but this approach isn't working right. Thanks for your help Anello I am working on a Phonegap app that sends emails that consist of form data that is filled out within the app. I need my app to send the emails which I have sorted out. The second part of the app needs to store the email subject of all the mails that are sent in local storage and then in a separate function needs to output all the saved data and send it. I will post my full code below and comment the important bits. Code: function sendMail(imageURI, click){ var d = new Date(); var dat = d.getDate(); var mon = d.getMonth(); var year = d.getFullYear(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var todayDate = dat+'-'+mon+'-'+year+' | '+hours+':'+minutes+':'+seconds; var agent = $('#agent').val(); var depot = $('#selection').val(); var date = $('#free').val(); var newURI = imageURI.replace("file:///storage/emulated/0/DCIM/Camera/",""); /* -----> the variable that needs to be stored */ var newFileName = 'N' + result + '_' + agent + '_' + todayDate + '_' + newURI + '_' + depot + '_' + date; /* -----> storing the variable */ var temp = localStorage.getItem('newFileName'); var somearray=temp.split(','); somearray_length=somearray.length; somearray[somearray_length]=newFileName; var somestring=somearray.join(','); localStorage.setItem('newFileName',somestring); /* <----- storing the variable */ var largeImage = document.getElementById('largeImage'); largeImage.style.display = 'block'; largeImage.src = imageURI; cordova.plugins.email.addAlias('gmail', 'com.google.android.gm'); cordova.plugins.email.open({ app: 'gmail', to: 'blah@gmail.com', subject: newFileName, body: '<ul><li style="font-weight:bold;text-decoration: underline;"><b><u>File: </b></u></li><li>'+newURI+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Agent Name: </b></u></li><li>'+agent+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Next Scheduled Date: </b></u></li><li>'+date+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Scanned: </b></u></li><li>'+todayDate+'</li><br><li style="text-decoration: underline;font-weight:bold;"><b><u>Depot: </b></u></li><li>'+depot+'</li></ul>', attachments: [imageURI], isHtml: true }); }; /* -----> The second function */ function endOfDay(data){ var d = new Date(); var dat = d.getDate(); var mon = d.getMonth(); var year = d.getFullYear(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var todayDate = dat+'-'+mon+'-'+year+' | '+hours+':'+minutes+':'+seconds; ending=localStorage.getItem('newFileName'); var salesman = $('#agent').val(); var newsFileName = 'End of Day Report for Agent: ' + salesman + '|' + todayDate; cordova.plugins.email.addAlias('gmail', 'com.google.android.gm'); cordova.plugins.email.open({ app: 'gmail', to: 'seth.v.staden@gmail.com', subject: newsFileName, body: 'end of day report: <br>' + ending, isHtml: true }); localStorage.setItem('newFileName',''); }; my problem is that instead of outputting all the sent subjects that have been stored like so: "subject 1, subject 2, subject 3, etc..." it is outputting it as the latest mail that was sent, i.e. "subject 3, subject 3". I have no clue why this is going wrong or how to fix it... any help would be greatly appreciated. Reply With Quote 01-15-2015, 11:13 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Instead of doing all this tortu Code: var temp = localStorage.getItem('newFileName'); var somearray=temp.split(','); somearray_length=somearray.length; somearray[somearray_length]=newFileName; var somestring=somearray.join(','); localStorage.setItem('newFileName',somestring); Why not simply do Code: localStorage.setItem('newFileName', localStorage.getItem('newFileName') + "," + newFilename ); Though I admit I don't see why your code won't work. It just causes a bunch of unneeded overhead. ********** COMMENTARY: I think your dates will be unreadable by humans. var mon = d.getMonth(); That will get a ZERO for January, 1 for February, etc. For human readable, you should do var mon = d.getMonth() + 1; Hello all, I need some help here. I'm new to HTML 5 and I'm not sure how to convert my cookie script over to HTML 5 LocalStorage. If anyone could help, I would appreciate it greatly. Here's my cookie script: Code: var currentRotation=null; function checkOrientAndLocation(){ if(currentRotation != window.orientation){ setOrientation(); } } function setOrientation(){ switch(window.orientation){ case 0: orient = 'portrait'; break; case 90: orient = 'landscape'; break; case -90: orient = 'landscape'; break; } currentRotation = window.orientation; document.body.setAttribute("orient",orient); setTimeout(scrollTo,0,0,1); } $(window).unload(function() { // On page unload $('.remember').each(function() { // Save each value to expire in a year $.cookie(this.id, this.value, {expires: 365}); }); $('.draggable').each(function() { // Save draggable positions var draggable = $(this); $.cookie(this.id, draggable.css('top') + '_' + draggable.css('left'), {expires: 365}); $.cookie('disp' + this.id, draggable.css('display'), {expires: 365}); }); }); $(function() { var val, pos, disp; setInterval(checkOrientAndLocation,1000); $('.remember').each(function() { var val = $.cookie(this.id); // Retrieve value for this element if (val) { this.value = val; } } ); $('.draggable').each(function() { var pos = $.cookie(this.id); // Retrieve values for this element if (pos) { pos = pos.split('_'); $(this).css({position: 'absolute', top: pos[0], left: pos[1]}); } var disp = $.cookie('disp' + this.id); if (disp) { this.style.display = disp; } } ).touch({animate: false, sticky: false, dragx: true, dragy: true, rotate: false, resort: false, scale: false }); }); I'm trying my hand at localstorage (which is HTML5), but I'm combining it with javascript (which is... erm, well, javascript ) so I decided to put this in the javascript forum. If I'm wrong, I apologize. Anyway, though I'm not a complete newbie when it comes to coding, this is new for me and frankly, I'm stuck. What I'm trying to do (nothing special, just messing around a bit) is show the current time and the time the visitor last visited. I made this: Code: var tijd = new Date(); var oudetijd = tijd.getTime(); localStorage.setItem('laatste bezoek', oudetijd); var laatstebezoek = localStorage.getItem('laatste bezoek'); document.write(laatstebezoek + "<br>"); document.write(oudetijd); Should work, right? Well, it does... partly. It shows the current time (woohoo!!! ) but the "old time" (oudetijd) is exactely the same! Now, I know I'm doing something wrong here, most likely something stupid like a missing comma, but whatever it is, I don't see it. Can someone shed some light on this? P.S. As you can probably see from the code, I'm Dutch. I dont know if it helps or not, but here's a translation: tijd= time oude tijd = old time laatste bezoek = last visit Thanks in advance! So. When I save a boolean to localStorage It converts it to string. PHP Code: localStorage["fixedBackground"] = document.getElementById("fBackground").checked; And that saves a 'true' or 'false' string. So to convert it to a boolean value, in the 'restore options' I use the function 'toBool' PHP Code: function toBool(str) { if ("false" === str) return false; else return str; } PHP Code: var value = localStorage["fixedBackground"]; if (null != value) document.getElementById("fBackground").checked = toBool(value); And that works just fine. However, I want to recall this saved data in a javascript. I want an PHP Code: if (value = true){ document.getElementsByTagName('body')[0].style.backgroundAttachment="fixed"; } But I can't get a 'toBool' type of function into that statement This is my method of retrieving the data: PHP Code: var port = chrome.extension.connect({name: "knockknock"}); port.postMessage({get: "fixedBackground"}); port.onMessage.addListener(function(msg) { //Set bgimage attachment javascript:value=msg.value; which makes the full if statement: PHP Code: var port = chrome.extension.connect({name: "knockknock"}); port.postMessage({get: "fixedBackground"}); port.onMessage.addListener(function(msg) { //Set bgimage attachment javascript:value=msg.value; if(value = true) { document.getElementsByTagName('body')[0].style.backgroundAttachment="fixed"; } }); any ideas? Howdy So i am working on a piece that using local storage and saves them to an un ordered list. I have been using Chrome for the console and inspector abilities and it has been going well. I've tested it before in Safari and Opera and I know it works. However, in Firefox (and IE but I don't care about that) I am getting a console error. Here is the code being executed: Code: var i=0; while (localStorage.key(i) != null) { var values = localStorage.getItem(localStorage.key(i)); values = values.split(";"); $("#logscreen").append("<li class='arrow logname'><a href='#' class='direct' onclick='...'>" + values[0] + "</a></li>"); i++; } There is some jQuery thrown in there but basically it says, test for a localStorage key of i, if it is not null create the list item, add one to i and repeat. I am getting the following error in firefox only: Index or size is negative or greater than the allowed amount" code: "1 [Break on this error] while (localStorage.key(i) != null) Any ideas folks? Hey there. I've recently written a small javascript library that creates a unified interface for localStorage and sessionStorage. The code is here http://github.com/AndrewLowther/StorageItem I'm looking for people to give me feedback and to help me work on it should you so wish. Feedback is most welcome! Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? Ignore post (if mod, please delete)
Hello. Is there any way to get the variable name of an object from inside the object? E.g. PHP Code: function Bla(){ this.write = function(){ document.write(<objectname>); } } obj1 = new Bla(); obj1.write(); //Outputs obj1 Here is my script: PHP Code: function myTimer(seconds, obj){ this.seconds = seconds; this.obj = obj; this.startTimer = function(){ if(this.seconds>0){ this.seconds--; this.obj.innerHTML = this.seconds; this.timer = setTimeout("Timer.start()",1000); } } } Timer = new Timer(10, obj); Timer.startTimer(); Now the problem is that the variable that contains the object must be named "Timer". This way I cannot create new timer objects with different variable names I have tried: this.timer = setTimeout("this.start()",1000); but it doesn't work. That's why it would be good to detect the variable name and instead use something like this: this.timer = setTimeout(varname+".start()",1000); I would rather not have to pass the variable name through a parameter like this: Timer1 = new Timer(10, obj, "Timer1"); Thanks in advance. Quote: menu: function( a, b ) { $( b ).observe( 'click', function( event ) { event.stop(); if( $( a ).visible() ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } else { $( a ).show(); $( b ).addClassName( 'selected' ); document.observe( 'click', function( e ) { if( e.target.id != a && e.target.id != b && !Element.descendantOf( e.target, $( a ) ) ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } }); } }); $$( '#' + b + ' > a' ).each( function( element ) { element.observe( 'click', function( event ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); }); }); } This work's perfrect accept when i use it with others on the menu it leaves the other ones open, how do i get it to close the open one when i open a new menu.. Thanks. hi, i am working on an online store, i have a list of items in the store and i want a receipt containing the items selected from my store for purchase with their price and other details generated after the order is place. I want to achieve this using javascript... Please help out.
I'm new to using cookies. I am using JavaScript for a web project and I'm using cookies and I have 5 links for different movie trailers and I have a trailers.html page with a div with a id="movie" and want to know so that when you click on a Movie trailer link so that it stores a value in a cookie so that you can check on the trailers page which trailer was chosen and display in the div tag
Hi all Is there a way in Javascript to store a value to different variables in 1 command, something like: Code: Store 50 to nHeight,nWidth,nTop; or nHeight=nWidth=nTop=50; What I try to do is avoid errors by typing the value only once in code. I could do the following, but thought there might be a more direct way: Code: var nValueToStore = 50; nHeight = nValueToStore ; nWidth = nValueToStore ; nTop = nValueToStore ; Hi, I just found this forum and I am hoping that someone will be able to help me. I am building a store locator for a website that I maintain; I am using a G! example http://code.google.com/apis/maps/art...sqlsearch.html. However, there seems to be some issues that I can't find... I have looked until I go blind... this is the php code that I am using: Code: <?php require("stores.php"); // Get parameters from URL $center_lat = $_GET["lat"]; $center_lng = $_GET["lng"]; $radius = $_GET["radius"]; // Start XML file, create parent node $dom = new DOMDocument("1.0"); $node = $dom->createElement("markers"); $parnode = $dom->appendChild($node); // Opens a connection to a mySQL server $connection=mysql_connect (localhost, $username, $password); if (!$connection) { die("Not connected : " . mysql_error()); } // Set the active mySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ("Can\'t use db : " . mysql_error()); } // Search the rows in the markers table $query = sprintf("SELECT name, address, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20", mysql_real_escape_string($center_lat), mysql_real_escape_string($center_lng), mysql_real_escape_string($center_lat), mysql_real_escape_string($radius)); $result = mysql_query($query); $result = mysql_query($query); if (!$result) { die("Invalid query: " . mysql_error()); } // Iterate through the rows, adding XML nodes for each while ($row = @mysql_fetch_assoc($result)){ $node = $dom->createElement("marker"); $newnode = $parnode->appendChild($node); $newnode->setAttribute("name", $row['name']); $newnode->setAttribute("address", $row['address']); $newnode->setAttribute("lat", $row['lat']); $newnode->setAttribute("lng", $row['lng']); $newnode->setAttribute("distance", $row['distance']); } echo $dom->saveXML(); ?> And this is the java that I am using: Code: <script type="text/javascript"> //<![CDATA[ var map; var geocoder; function load() { if (GBrowserIsCompatible()) { geocoder = new GClientGeocoder(); map = new GMap2(document.getElementById('map')); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(40, -100), 4); } } function searchLocations() { var address = document.getElementById('addressInput').value; geocoder.getLatLng(address, function(latlng) { if (!latlng) { alert(address + ' not found'); } else { searchLocationsNear(latlng); } }); } function searchLocationsNear(center) { var radius = document.getElementById('radiusSelect').value; var searchUrl = 'findstores.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; GDownloadUrl(searchUrl, function(data) { var xml = GXml.parse(data); var markers = xml.documentElement.getElementsByTagName('marker'); map.clearOverlays(); var sidebar = document.getElementById('sidebar'); sidebar.innerHTML = ''; if (markers.length == 0) { sidebar.innerHTML = 'No results found.'; map.setCenter(new GLatLng(40, -100), 4); return; } var bounds = new GLatLngBounds(); for (var i = 0; i < markers.length; i++) { var name = markers[i].getAttribute('name'); var address = markers[i].getAttribute('address'); var distance = parseFloat(markers[i].getAttribute('distance')); var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng'))); var marker = createMarker(point, name, address); map.addOverlay(marker); var sidebarEntry = createSidebarEntry(marker, name, address, distance); sidebar.appendChild(sidebarEntry); bounds.extend(point); } map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); }); } function createMarker(point, name, address) { var marker = new GMarker(point, icon); var html = '<b>' + name + '</b> <br/>' + address; GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); }); return marker; } function createSidebarEntry(marker, name, address, distance) { var div = document.createElement('div'); var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address; div.innerHTML = html; div.style.cursor = 'pointer'; div.style.marginBottom = '5px'; GEvent.addDomListener(div, 'click', function() { GEvent.trigger(marker, 'click'); }); GEvent.addDomListener(div, 'mouseover', function() { div.style.backgroundColor = '#eee'; }); GEvent.addDomListener(div, 'mouseout', function() { div.style.backgroundColor = '#fff'; }); return div; } //]]> </script> I am at a complete loose as to where the problem lies. Thanks in advance for any help you can give me. |