JavaScript - Localstorage Boolean Values.
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? 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 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; 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? 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! 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 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, I'm trying to modify this function: Code: function togglePoly(poly_num) { if (document.getElementById(poly_num)) { if (document.getElementById(poly_num).checked) { gpolys[poly_num].show(); } else { gpolys[poly_num].hide(); } } } which works for a checkbox to one that works for a button. I guess I'm stuck on what to replace "checked" with there in the 3rd line. is there some one word answer, or do I need to I rewrite the function to be more button-friendly? thanks in advance This is perhaps a somewhat trivial point but it's bugged me a couple of times recently and I wondered if anyone out there had any thoughts on the matter. Essentially I have an action that can happen many times but I want to record whether it has happened at least once. I know we are talking about a trivial amount of processing and code here but is there any real difference between the following two methods: Code: myCheck: false, myRepeatedlyCalledFunction: function() { this.myCheck = true; // do some stuff } vs Code: myCheck: false, myRepeatedlyCalledFunction: function() { if(this.myCheck === false) { this.myCheck = true; } // do some stuff } thoughts? I am about to translate some C++ code to JavaScript. In C++, it is straightforward to declare and use a Boolean variable; all I do is swap it between true and false and back again as needed. For example, Code: // C++ Code . . . bool na = 1; . . . na = !na; . . . I am wondering if JavaScript offers boolean variables. As far as I know, it does not, but I thought I would confirm by asking around. At the moment, I am planning to code the comparable block in Javascript using an "if" statement or a ternary operation. For example, Code: JavaScript Code . . . var na = 1; // Option 1 if (na) na = 0; else na = 1; // Option 2 na = ((na) ? 0 : 1); . . . Is one of these options recommended as the best way to simulate a boolean variable and operation? (I would like the fastest-executing code possible.) Or is there another--better--way to do it? All advice and recommendations appreciated. Thank-you in advance. Hello. If the function called Change has ever been called, the function in window onload is to not be executed. This is what I have so far, but I am sure it's wrong or missing something. I tried to confirm the results with document.write or alert but am having trouble doing so. Code: window.onload=function(){ if (calledAtLeastOnce == false) { Change('big', 'http://www.adomainname.com/image.jpg'); } } function Change(id,src,w,h){ var calledAtLeastOnce = true; } Hello everyone! I'm currently doing an assignment which involves a snack machine. I'm currently working on the PacketOfCrisp class. It needs to start with 10 crisps, and have a boolean field for whether or not it's closed. This field is called open and is obviously set to false when the object is created. It also needs to give out some messages, ie if the packet is not open then a message should appear saying that the packet is closed. If the pack has no crisps left a message should appear saying as such. Other than that when selecting eatCrisp the amount of crisps in the packet should go down by one. Here is what I have so far: Code: public void eatCrisp() { if(open = false) { System.out.println("Open packet"); } else if (open = true && numOfCrisps >= 1) { numOfCrisps = numOfCrisps - 1; } else { System.out.println("No Crisps!"); } } Now for some reason when I invoke eatCrisp it takes out a crisp and changes the "open" field of the object to true and I can't figure out why. As far as I can figure it should be giving me a message of "Open packet" until I open the packet with the "openPacket" method, but instead "eatCrisp" is doing that by itself. Any ideas? Hi, I am very new to javascript and html. I am trying to create a function which will hide or show a div (div1). Right now, it is always showing the div whether the boolean value is true or false. I know that it is getting inside the else if part, but it doesn't seem to be working. Code: <script type="text/javascript"> function hideDiv(flag) { if (flag == false) { document.getElementById('div1').style.visibility="visible"; } else if (flag == true) { document.getElementById(div1).style.visibility="hidden"; } } var bool = new Boolean(true) hideDiv(bool); </script> <body> <div id="div1"> Text! </div> </body> Thank you for taking a look Hello fellow programmers, I am having some trouble with my javascript doing what I want it to, which is returning values (true/false || 1/0). I haven't used much javasript but I am experienced with C#, Java, Python etc so this is sort of new to me syntax wise. Here is what I have so far: http://jsfiddle.net/HpSyJ/1/ note: for some reason css doesn't like jsfiddle :S, the error messages are hidden in my Notepad++ & firefox combo though Really all I want is when I hit submit, it runs an alert or changes the error message to visible. Can someone please have a quick read over and see if anything jumps out at them? Thanks in advance, Andrew Hi gud mng, I have one problem... How to process textbox values/ call textbox values in JS through a Java program. My text box values are dates. I have to process these dates. Like in online banking we select day to know our transactions. After submitting we get results. remember my files are in my directory only. No need of database. My files are look like 20100929, 20100930, 20101001 For epoch_classes.js, epoch_styles.css u can download coding from this link : http://www.javascriptkit.com/script/...ch/index.shtml Code: Code: <html> <table width="900" border="0" cellpadding="10" cellspacing="10" style="padding:0"> <tr><td id="leftcolumn" width="170" align="left" valign="top"> <div style="margin-left:0px;margin-top:0px"><h3 class="left"><span class="left_h2">Select Option</span></h3> <a rel="nofollow" target="_top" href="day_wise.htm" >Day-wise</a><br /> <br /> <a rel="nofollow" target="_top" href="between.htm" >Between Days</a> <link rel="stylesheet" type="text/css" href="epoch_styles.css" /> <script type="text/javascript" src="epoch_classes.js"></script> <script type="text/javascript"> var cal1, cal2; window.onload = function () { cal1= new Epoch('epoch_popup','popup',document.getElementById('popup_container1')); cal2= new Epoch('epoch_popup','popup',document.getElementById('popup_container2')); }; /*............*/ function confirmation(f) { var startdate = f.fromdate.value var enddate = f.todate.value var myday=new Date() var yr=myday.getFullYear() var mn=myday.getMonth()+1 var dt=myday.getDate() var today="" var present, ys, ms, ds, ye,me,de, start, end if(mn < 10) { mn = "0" + mn } if(dt <10) { dt = "0" + dt } today= yr + "/" + mn + "/" + dt present=yr + "/" + mn + "/" +dt if (today < startdate ) { alert (" Start date should not be exceed to-day's date " + present ) startdate.focus() return false } if (today < enddate ) { alert (" End date should not be exceed to-day's date " + present ) enddate.focus() return false } if (today == startdate ) { alert(" You are selected to-days date as Starting day" ); } var answer = confirm("Do you want to continue ?") if (answer) { if( startdate < enddate) alert("Dates between " + startdate + " to " + enddate + " are confirmed" ) else alert("Dates between " + enddate + " to " + startdate + " are confirmed" ) } else { alert("Date not confirmed") window.location="to_date.htm"; } ys= startdate.substring(0,4); ms= startdate.substring(5,7); ds= startdate.substring(8,10); start=ys + "" + ms + "" +ds ye= enddate.substring(0,4); me= enddate.substring(5,7); de= enddate.substring(8,10); end=ye + "" + me + "" +de } /*.......................................................*/ </script> <div style="margin-left:100px;"> <body> <style type="text/css"> #conf { margin-left:115px; } </style> <td align="left" valign="top"> <table width="100" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:0px"> </table> <h4>From Date</h4> <form name= "formbet" id="placeholder" method="post" action="#" > <input id="popup_container1" type="text" name= "fromdate" maxlength="10" size="20"/> <td align="left" valign="top"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:20px"> <h4>To Date</h4> <input id="popup_container2" type="text" name= "todate" maxlength="10" size="20"/> <br /> <br /> <input id="conf" type="button" onclick="confirmation(this.form)" value="Submit"> </form> </body> </html> In my coding, ys, ms, ds represents year starting, month starting, starting day... ye, me, de represents end... start,end gives file names in the format of yyyymmdd now i want to process files from 20100101 to 20100930 means from date is 2010/01/01 and to date is 2010/09/30 if i press submit button the files from 20100101 to 20100930 are processes here ys=2010 ms=01 ds =01 and ye=2010 me=09 de= 30 For this how do i call these textbox values (from date text box and todate) to another program (java) Thanks in advance. I have a bunch of checkboxes like below that the user can check some or all and click the button and see the values of all the selected checkboxes. How can I do that? Code: <script> function alertValues(){ } </script> <input type="checkbox" class ="normal2" value="131971" name="list[]" > <input type="checkbox" class ="normal2" value="131973" name="list[]" > <input type="checkbox" class ="normal2" value="131975" name="list[]" > <input type="checkbox" class ="normal2" value="131977" name="list[]" > <input type="button" onClick="alertValues()" Hi, What's a good way/ideal data structure to achieve this? The objective of the code/function is to map user-inputted strings into a pair of specific, hard-coded strings. For example, say the user types "firefox" or "ff", or "fx". The output would be the pair ["browser", "mozilla"], for example. I'm currently using a multidimensional array, but it feels inefficient and I'm having trouble mapping an arbitrary number of inputs into 2 outputs. Code: var strings = [ ["input1", "output1a"], ["input2", "output1a"], ["input3", "output1a"], ["input1", "output1b"], ["input2", "output1b"], ["input3", "output1b"] ]; How should I map the elements ["input1", "input2", "input3"] => ["output1a", "output1b"] ? Another method I used previously was a massive switch statement. This fulfills my needs, but I'm not sure about the efficiency (though if I remember correctly, switch statements become more efficient as size grows, since it uses a hash table?). Code: switch (input) { case "ff": case "firefox": case "fx" : case "ffox": return ["browser", "mozilla"]; case "ie": case "internet explorer": return ["browser", "microsoft"]; ... } i am making a mock website where the user make their own computer by selecting items from drop down menus. then a value of the item comes up below. this works but i am having trouble adding the numbers up for the total cost. here is my code <html><head><title>build</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css"> </style></head> <body> <script type="text/javascript"> var motherboard = new Array( '74', '50', '73', '106', '269', '64', '55', '135', '47', '79', '118', '163'); var cpu = new Array( '88', '104', '168', '352'); function changeMotherboard(Mid) { var ind = document.getElementById(Mid).selectedIndex; document.getElementById("motherboardDisplay").innerHTML=motherboard[ind]; } function changeCpu(Cid) { var ind = document.getElementById(Cid).selectedIndex; document.getElementById("cpuDisplay").innerHTML=cpu[ind]; } </script> </head><body> <form> Motherboard <select id="motherboard" onChange="changeMotherboard('motherboard');"> <option value="0">Asus P5G41C-M-LX G41 DDR2+DDR3</option> <option value="1">MSI G41M-P33 </option> <option value="2">Asus P5P41T-LE </option> <option>G-B H55M-S2H</option> <option>Asus P7P55D-E-Deluxe</option> <option>Asus M2N68-AM Plus </option> <option>ASRock N68S3-UCC </option> <option>Asus M4A88TD-M-EVO-USB3</option> </select><br> </form> <div id="motherboardDisplay">Select from the list to see price</div> <form> CPU <select name="cpu" id="cpu" onChange="changeCpu('cpu');"> <option value="0">E6500</option> <option value="1">Core G6950</option> <option value="2">i3-550</option> <option>Core i7-930</option> </select> <br> </form> <div id="cpuDisplay" type = text>Select from the list to see price</div> <p> </p> <p> </body> </html> hello I am having a problem to add numbers store in an array. arrayValues[0][0] = 1; arrayValues[0][1] = 2; var col = 0; var sum; for ( var row = 0; row < index; i++ ) sum += arrayValues[col][row]; my result is ==> 12 it is defining my sum variable as string. even I try do do this var sum = 0; to define sum as numeric variable. my result was ==>012. Any idea, this is my first javaScritp code. Thanks. Hi There, I need your help. I am capable of getting all the field headers in my excel document but am now unable to get their respective field values. Any idea as to what I am doing wrong? Code: //======================================================================== function v8_export() { //======================================================================== var excel = new ActiveXObject("Excel.Application") var book = excel.Workbooks.Add() var sheet = book.Sheets(1); //sheet.Range("A2").Value = "Hello World" //WRITE COLUMN HEADERS: sheet.Columns("A:P").ColumnWidth = '15' for (var c = 0; c < rs.fields.count; ++c) { sheet.Cells(4, c + 1).Value = rs.fields(c).name } //WRITE FIELD VALUES: var row = 1 for (var c = 0; c < rs.fields.count) { sheet.range('A' + row).value = rs.fields(c).value row = row + 1 } rs.MoveNext excel.Visible = true }//end of function v8_export() Thanks. J |