JavaScript - Out Localstorage For A Specific Key
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; Similar TutorialsHello 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 }); }); Hello, 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'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! 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? 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 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? 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! Another thing that has been driving me crazy is that css positioning is handled differently by different browsers. JS is not my area, but I can do a lot with CSS, and I do, but cross browser compatibility is killing me. I can use an IF IE statement and only IE runs that segment of code, but I haven't been able to figure out out how to make ONLY firefox or ONLY opera or safari enact an encapsulated segment of code. The same type of IF statement doesn't work for them. Is there a single method using JS that works for all browsers? Thre is probably a very simple answer and I am just missing it somehow. Hey, I'm working on a large demo created with html/css. It has well over a hundred pages with a left column navigation of normal links. I am trying to make this demo product specific with a page asking what product they are using before they enter the demo. Based on the users selection I want to have some of the pages be more product specific with different content and hide some pages. To create this I could just duplicate my html files to have one for each product with its respective navigation (basically resulting in two seperate demos). That however would be a nightmare for future updates. Anyone know how to script this? Any help would be awesome! I am having a problem with my homework displaying an iframe using JavaScript. My homework states: Insert a script element that does the following: part a. Insert the following multiline comment: Display the daily schedule in an inline frame. Daily schedules are stored in the files sunday.html through saturday.htm. part b. Insert a command to write the HTML code <iframe src="weekday.htm'></iframe> to the Web page, where weekday is the text string returned by the weekDay() function. What I have so far: <script type= "text/javascript"> /* Display part a */ document.write("<iframe src='weekday.htm'></iframe">; </script> My Question: How do I display weekday.htm within my script on a specific day using the function weekDay() function. below is my weekDay() function: function weekDay(){ thisDate = new Date(); var thisWDay=thisDate.getDay(); var wdName = new Array("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"); return wdName[thisWDay]; } Is it possible to use Javascript to uncheck all checkboxes that appear within a specific div? I'm already using names/ids for each checkbox, and these are generated dynamically, so I cant really apply a group to all the checkboxes I want to untick. I am looking for a specific JS which calculates the number of pets killed today in CA as well as the amount of taxpayer dollars spent - similar to the ones made for those who have quit smoking, how many cigarettes they have not smoked, how much money they have saved, etc. The starting point would be January 1, 2010 and each day it would take the number of days so far in the year times two known factors. I know the state kills 786 pets a day as well as the daily cost to taxpayers is $392,671. Even two different scripts would work for us. I want to drop this JS or html onto a page similar to the Doomsday clock as a shock value to those who aren't aware of how many pets have had to die so far this year or how many taxpayer dollars were spent to house, feed and adopt and/or kill those pets not adopted in our state. HELP! I know enough JS and HTML to be dangerous (as you can see from our website - http://www.tinylovingcanines.org) so as much as I search and try to build one myself, I can't get seem to make this project work. THANK YOU for any help!!! Hi there! I've been searching for threads to solve my problem but I don't have the knowledge necessary to figure it out (you know, graphic designers....) so your help will be very appreciated!!! Here's the problem : I have a div named "cat" that I want to hide with a Javascript:animatedcollapse (slideup) action. The action is linked externally on another page. This is the line/link that hides it : <a href="javascript:animatedcollapse.hide('cat')">Hide the div<br/> It works fine. But, I want this action to happen at the same time that you press another link (that other link opens a page in an iframe). This is the iframe link : <p><a href="page.html" target="iframe">Open link in iframe</a></p> Both links work fine. But i want to merge the two together. How? Thanks in advance! I can't seem to find what I need but I know it exists. I trying to find a vertical scroller that will automatically have the text scroll upwards but have an arrow above and arrow below to be able to control the direction of the scrolling text, or a script with no arrows but still allow me to take control by mousing over the text to scroll up or down. Thanks Ok, here is the scenario... We have a commercial shopping cart software installed on our website and since it is proprietary, we do not have access to source code. But they do allow you to include custom javascript on the web pages that they generate. What I want to do is add some text after a specifc INPUT tag that appears on the page within a TD tag. The problem is, that they do not have any specifc ID assigned to the INPUT or TD tag, and although the INPUT tag has a name assigned to it, the name is used in other tags as well and is not unique. Below is the code that I used to solve the problem, but I want to know if there is a more efficient way to do it... Basically my code grabs every TD tag on the page, and then loops thru all of them looking for the specifc INPUT tag characteristics and then inserts the text afterwards (it needs to work in both Firefox and IE so you cannot use innerHTML). Thanks in advance for any suggestions! Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <meta name="generator" content="PSPad editor, www.pspad.com"> <title></title> <script type="text/javascript"> function myLoad() { var _match = false; var _tdcells = document.getElementsByTagName('td'); var _len = _tdcells.length; for (var _i=0; _i<_len; _i++) { _child = _tdcells[_i].childNodes; _child_len = _child.length; for (_j=0; _j<_child_len; _j++) { if ( (_child[_j].nodeType == 1) && (_child[_j].attributes.getNamedItem('name').value == 'zip_code') && (_child[_j].attributes.getNamedItem('onchange').value == 'zip_changed();') && (_child[_j].attributes.getNamedItem('type').value == 'text') && (_child[_j].attributes.getNamedItem('size').value == '10')) { _cell = _i + 1; alert('Found a match in cell number '+_cell); _match = true; var old_node = _child[_j]; var new_node = document.createTextNode(' New Text!'); //Insert Before usually inserts before the element, but using targetElement.nextSibling inserts it after instead!! _tdcells[_i].insertBefore(new_node, old_node.nextSibling); } } } if (_match !== true) { alert('no match found'); } } </script> </head> <body onLoad="myLoad();"> <table class="zipncountry" border="1"> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table> <br> <table border="3"> <tr> <td>4</td> <td>5</td> <td><input type="text" name="zip_code" value="123" size=10 maxlength=20 onChange="zip_changed();"><input type="hidden" name=zip_code value="321" size=10 maxlength=20 ></td> </tr> </table> <br> <table class="zipncountry" border="5"> <tr> <td>7</td> <td>8</td> <td>9</td> </tr> </table> </body> </html> Hello everyone, wondering if I could get some help. I have not done anything with html and javascript until this afternoon and funnily enough I'm struggling a tad I am creating a free website about the dangers of chocolate for dogs. Basically I need a calculator to calculate the toxic amount for the user input of their dogs weight in kgs. I figured doing one for each type of chocolate would be easier than doing something where a box was ticked for each type of chocolate so have been trying to do one for milk chocolate first. This is my feeble attempt, it looks good but doesnt work, my javascript is clearly majorly wrong somewhere! <html> <head> <script language="JavaScript"> function calc(form) { var f = parseFloat(form.kg.value); var T = 0; T = (f/0.45)*28.35; form.answer.value = T; } // done hiding from old browsers --> </script> </head> <body> <FORM> <h2>Toxic dose of milk chocolate</h2> Enter dogs weight in kg: <INPUT NAME="kg" VALUE="0" MAXLENGTH="100" SIZE=25> <p> Click to calculate toxic dose in grammes: <INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON onClick=kg(this.form)> <p> Toxic amount of milk chocolate is: <INPUT NAME="g" READONLY SIZE=25> </FORM> </body> </html> Can anybody help? Thanks in advance. Hi, I'll explain my situation: I'm completely new to javascript so what i want to do is make a script that shows a specific div when the visitor is at the homepage but hide it when hes in another page of my website. i've read some people trying to explain it to someone else but it seems that i need to learn many aspects of the javascript language to edit it to my needs. I'm a med student and im really tight in my schedule and have almost no extra time to sit and read about javascript just so i can do this one specific thing. Would you please help me out? I've been trying to figure this out on my own for the past 3 days with no success. I will greatly appreciate it if someone helps me. PLEASE... Hi I'm relatively new to Javascript and I'm trying to learn more about dates my problem is as follows I have to do validation on a form for 2 dates(StartDate and EndDate) the dates cannot be more than four months apart if they are an alert must be displayed. In other words Nov 2009 till March 2010 or May 2009 till September 2009 should be invalid regardless of the day of the month Simply 2 input boxes(StartDate and EndDate) and a submit I've got the other parts of my page worked out just this has me stumped I would appreciate any help in this regard Thank You for your time Hi to All, I have two menus, related each other, in this way: <head> var sum_db = new Object() sum_db["email1"] = [{value:"I01 - Problems of one level", text:"I01 - Problems of one level"}, {value:"I02 - Problems RDM", text:"I02 - Problems RDM"}, {value:"Free Text", text:"Free Text "}]; sum_db["email2"] = [{value:"I03 - Various", text:"I03 - Various"}]; // // function setIssue(chooser) { var newElem; var where = (navigator.appName == "Microsoft Internet Explorer") ? -1 : null; var Iss_Chooser = chooser.form.elements["iss_sum"]; while (Iss_Chooser.options.length) { Iss_Chooser.remove(0); } var choice = chooser.options[chooser.selectedIndex].value; var db = sum_db[choice]; if (choice == "email1") { newElem = document.createElement("option"); newElem.text = "Choose an issue ..."; newElem.value = "Choose Issue ..."; Iss_Chooser.add(newElem, where); } for (var i = 0; i < db.length; i++) { newElem = document.createElement("option"); newElem.text = db[i].text; newElem.value = db[i].value; Iss_Chooser.add(newElem, where); if ((choice == "email1") && (db[i].text.indexOf('Free Text')==0)) { document.getElementById("label_des").style.display=""; } else { document.getElementById("label_des").style.display="none"; } } } // </script> </head> <body> <form> <select size="1" name="mess" id="mess" onchange="setIssue(this)"> <option value="email1" selected>email1</option> <option value="email2">email2</option> </select> .... .... <select id="iss_sum" name="iss_sum"> <option value="<%=objRS("Issue_Summary")%>" selected><%=objRS("Issue_Summary")%></option> </select> <label for="iss_des" id="label_des" style="display:none; vertical-align:top">Description:<textarea id="iss_des" name="iss_des"><%=objRS("Issue_Description")%></textarea> </label> My problem is: I would like that if I select ONLY email1 and ONLY the option "Free Text", appears the textarea with label Description. Up to know if one selects email1, automatically the textarea appears near for every option; it seems that the condition of the if is not respected !!! Thanks a lot in advance !!! I have this simple php array. The array will dynamically pull results from the db in the future. PHP Code: <?php $dataArray = array ( 'id1' => array ( 'icon' => '<img src="images/piicon.png">', 'app' => 'GGP', 'timestamp' => date('m/d/y'), 'location' => 'Bellevue', 'comments' => 'It works!', ), 'id2' => array ( 'icon' => '<img src="images/piicon.png">', 'app' => 'Meijer', 'timestamp' => date('m/d/y'), 'location' => 'San diego', 'comments' => 'It works!', ), 'id3' => array ( 'icon' => '<img src="images/piicon.png">', 'app' => 'Point Inside', 'timestamp' => date('m/d/y'), 'location' => 'Boston', 'comments' => 'I guess its working? Maybe not exactly what we want yet though?!', ) ); echo json_encode($dataArray); ?> Currently if I have 100 results in my array, 100 results will be added to the table, 75 = 75 rows etc. What I am trying to plan out is a logical way to display one result from the array at a time. I am not looking for a chunk of jquery as an answer, better yet would be a plan/idea a programmer would you use to solve this. PHP Code: $(document).ready(function() { setInterval(function() { // get data $.ajax({ url: '/ajax/data.php', type: "GET", cache: false, error: function(data) { $("div#error").html('error: '+data); }, success: function(data) { var jsonObj = jQuery.parseJSON(data); jQuery.each(jsonObj, function(index, value) { var newRow = $("<tr><td>"+value.icon+"</td><td>"+value.app+"</td><td>"+value.timestamp+"</td><td>"+value.location+"</td><td>"+value.comments+"</td></tr>"); $("#mainTable tbody").prepend(newRow); }); } }); }, 5000); }); thanks |