Javascript: localStorage paralyzes if-statements? - javascript

Made a boolean variable "disableReplaceDate", used in if-statements. Have to save the variable somehow because the page reloads and I need to use it to "check a status" sort of, so it doesn't return to default every time the page reloads.
Then, to save myself a lot of time and trouble, because I can't send them in the URL as parameters(it's occupied already by a complicated java file which manipulates it all and I'm no good at java at all), I decided to use window.localStorage setItem, getItem and removeItem etc., so basically
var disableReplaceDate = false;
window.localStorage.setItem("dRD", false);
disableReplaceDate = window.localStorage.getItem("dRD");
But now the if-statement, which looked as follows:
if(disableReplaceDate == true){/*do some stuff*/}
didn't work anymore! But then when I changed it to
if(disableReplaceDate){/*do some stuff*/}
It starts working suddenly.
And if that wasn't uncanny enough, it won't do this for all if-statements using the variable, I tried changing them to (!disableReplaceDate) and such, but it doesn't make them work.
Why is this? And how do I solve it?

localStorage only stores strings. And "false" evaluates as true in a context where a boolean is needed (for example a if statement).
You should change
disableReplaceDate = window.localStorage.getItem("dRD");
to
disableReplaceDate = window.localStorage.getItem("dRD") === "true";

I think because the type of your variable is "string" see this
typeof(disableReplaceDate)
The output will be string
I think you need to test this way if(disableReplaceDate === "false")

Related

Boolean to string wherever present in code

I have an app platform which is developed on "Edge". And my app is built on eclipse. In javascript files of my code many times i have declared my variables with boolean. But to run app on platform i have to convert these boolean values to string like "true". Then only i can set it true. In a big code it is not good to convert boolean to string everywhere. So is it possible that wherever i am having boolean value it can detect and convert to string so that the app platform developed on Edge can understand it ?
Why would you try to print out boolean values in the first place? Check to see if value is boolean where you are alert(value);
For example,
var value = true; // Somewhere in code
if (value == true) { // Just check if value is true/false
alert("true");
} else {
alert("false");
}
Your approach is unnecessary and you are making the problem more complex then needs to be. There is no way to check if a value is boolean while the code is running, so you are going to have to change it everywhere you want alert("true"); Sadly, you can't hack this with a different approach.

How to get unique id from localStorage for delete button

I have been trying for getting an id from localStorage but unable to achieve it.
My localStorage inside events contains such as below.
[{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21","end":"2016-05-22"},{"id":"ef7","title":"haha","start":"2016-05-25","end":"2016-05-26"},{"id":"ef8","title":"asdas","start":"2016-05-20","end":"2016-05-21"},{"id":"ef9","title":"sdas","start":"2016-05-19","end":"2016-05-20"}]
Now i will provide 2 coding with different method that i have tried so far. For information, i look through into this topic: localstorage: Get specific localstorage value of which contains many items
but none works for me.
I did tried coding as below:
1st method:
$("#deleteEventYes").click(function(){
var indexDel = localStorage.getItem("events");
var deleteId = calEvent.id;
var result = localStorage.getItem("events");
function getItemHrefById(json, itemId){
return $(json).filter(function(){return this.id == itemId;})[0].href;
}
var href = getItemHrefById(result, deleteId);
alert(href); });
Above code show some kind of array method (i think) where i'm using indexDel to get item from localStorage (events) while deleteId i took from calEvent.id which is the id for the event that has been clicked for to be deleted. Other than that, i think you guys know what it is. However for this method, i use result variable instead of indexDel. Thus don't mind if i getItem from localStorage 2 times
2nd method:
for (var i = 0 ; i < indexDel.length ; i += 1) {
if(deleteId == indexDel[i].id) {
return indexDel[i];
console.log(deleteId);
console.log(indexDel[i]);
}
}
return null;
Above code is using custom loop i think. The declaration of variable for indexDel is still the same with first method. I try to use the refactoring method but it seems its hard for me to understand how is it to be done. Is it because my variable placement is wrong? or is it because it is not suitable for my case?
NOTE: I want to delete an event inside eventClick function, and so far i did retrieve the id and remove the event from the calendar based on id. However my only problem now is to match the deleted event id with the id inside my localStorage and remove the item. So far getting an id from the is quite complicated for me.
UPDATED
I already done something like this but still don't work. Anyone can tell me what went wrong here? It is not giving me any error but it just do nothing. Not even delete.
https://jsfiddle.net/v35a2o07/3/
Never mind. I think i figure it out :)
It is because i forgot to setItem & stringify it after using splice.
Here i can assume splice is the same as add/remove such wrote at w3school
http://www.w3schools.com/jsref/jsref_splice.asp
"The splice() method adds/removes items to/from an array, and returns the removed item(s)."
My final code is on this fiddle given: https://jsfiddle.net/v35a2o07/4/
So the concept is:
1) First step is declare one variable that parse your localStorage key such asvar items = JSON.parse(localStorage["events"]); so that you can use it for the loop
2) Use for loop to determine the length of localStorage based on localStorage key that we parse on No. 1
3) Use if statement to check the comparison between localStorage data with our desire data such as if(items[i].id == deleteId){
4) This is OPTIONAL but important. To enable you to check the comparison is right, create one alert or console.log() and stringify it because if you don't, you will only see [object,object]. The coding such as alert(JSON.stringify(items[i])+"<<<>>>"+deleteId); Make some else statement too if you want to be sure.
5) When all the conditions are correct, then you are ready to do some action to it. For my case, i just use splice() to delete it. It is also can be used to add item. I am not sure how is it done but try to search for it to get more info.
6) After splicing it, it is safely to break and get out from the loop.
7) This is important otherwise, it will not work. Don't forget to set it back to localStorage and stringify it such as localStorage.setItem('events', JSON.stringify(items));
That's it.
I wish this would help anyone that needs it. If i have make wrong statement or wrong concept, please make correction and clarify it for anyone.
Cheers.

Hidden input field not being updated properly

I am trying to get the referrer and update the referrer so that my users can go back to the page they came back from. I have a hidden input field which holds the value of the redirect. I have a static value in there just in case the referrer is empty. If the referrer is not empty, I want to update the value of it. Here is the code I have written, I even tested it and it said it was updated, however, I am not being redirected properly, so it is not working.
JavaScript and HTML I have written (keep in mind, I have correctly linked the file and such):
$(document).ready(function(){
if (document.referrer != "") {
document.getElementsByName("redirect").value = document.referrer;
var test = "false";
if (document.getElementsByName("redirect").value == document.referrer){
test = "true";
}
alert(test);
}
});
<script src="js/referrer.js"></script>
<input type="hidden" name="redirect" value="https://www.google.com" />
I feel like this is a minor error or there might be some sort of standard I am not following.
Thanks for the help! I appreciate any insight!
I can't see what the problem is off hand by what you've given me. But what I can say is that if you are going to use JQuery in one place (document ready function) then you should also use it to grab the value of your input field.
It would also help if you put an Id on the input field instead of doing it by name. Ids are the best way to get a specific element. That could be your problem too.
Then call it using:
$("#ID").val()
so your code would become:
if($("#ID").val() === document.referrer)
I would also suggest using triple equals as well. But that is completely up to you.
I've never done anything with document.referrer, but there might be a better way of doing that as well.
One odd thing is that you are setting these 2 things equal to each other
document.getElementsByName("redirect").value = document.referrer;
and then immediately testing if they're equal to each other.
if (document.getElementsByName("redirect").value == document.referrer)
I can't say that this is your issue, but it's bad coding and should be fixed.
I think a single letter is tripping you up here.
if (document.getElement**s**ByName("redirect").value == document.referrer){
There's no singular equivalent for 'byName', so you do end up with an array (or at least, an array-like object). Unlike IDs, it is allowable for multiple inputs to have the same name. The easiest solution is this:
if (document.getElementsByName("redirect")[0].value == document.referrer){
Doing document.getElementsByName will return an object array that DOES NOT include the value. There is no way to change the value (That I know of and have tried) when using the getElementsByName. I have solved this issue by using getElementById, it actually works properly for me.

Workaround for not being able to save booleans with HTML5 Web Storage

I'm currently making a Mario-esque game with Javascript, or more precisely, CraftyJS.
I've looked here as reference,
and understand how to save values inputed by the user.
But what I want to accomplish is to save certain booleans(is that what they are called?) automatically, or when the player presses a save button or something.
For example, I have a dungeon called dungeon1, and I create a variable to represent whether or not the dungeon has been completed.
It's var dungeon1 = false; by default.
But when the player completes dungeon1, it changes to var dungeon1 = true;,
resulting in new additions to the world map, such as a portal to dungeon2(this is working fine).
What I want to save is this var dungeon1 = true; statement, so that when the user opens the game again, the dungeons completed will be loaded and the corresponding unlocks will be shown correctly. How would I do so?
Is there a way to say, make a save management file called save.js, then store booleans such as the one above once they become true?
You would just store the string version of the boolean that you want.
So store "true" and "false", and instead of checking just like if(variable) you'd have to check in the form of if(variable === "true"). Its a little derpy but you can see how it doesn't really add more complexity to your code.
If that type of if checking just offends your sensibilities, then in the code where you "get" it from the localStorage you could then recast it to a boolean.
var bool = (localStorage.getItem("myItem") === "true")
PS. you can setItem with booleans... it will just cast them to strings :D because most things it calls toString() on to store them if they aren't already strings.
So you can do:
enter code herelocalStorage.setItem("myItem", true)

sessionStorage isn't working as expected

Here is my code:
sessionStorage.loggedIn = true;
if (sessionStorage.loggedIn) {
alert('true');
}
else {
alert('false');
}
Simple enough. There must be some small thing I'm not understanding about how JavaScript is evaluating these expressions. When I put sessionStorage.loggedIn = false, the "false" alert shows correctly. However, when I change sessionStorage.loggedIn to true, the "false" alert still pops, even after clearing the session. What am I not getting right with this expression? It seems so simple, maybe I just need another pair of eyes on it.
Try to change your code to
sessionStorage.setItem('loggedIn',JSON.stringify(true));
if (JSON.parse(sessionStorage.getItem('loggedIn'))) {
alert('true');
}
else {
alert('false');
}
and it should work consistently across all major browsers.
The interface with the setItem/getItem methods is how the spec is written, so going that way is safer than using the shortcut of assigning properties. Also, sessionStorage, like localStorage is a textbased storage mechanism, and not meant for storing objects, so you need to wrap calls with JSON.parse and JSON.stringify to get the expected results across the board.
Be aware that JSON.parse doesn't always play nice with undefined/null values, so it might be wise to do some type checking first.
You can read the spec for the storage interface here
Keys and Values in a WebStorage object (sessionStorage) must be strings. If they are not strings they "should" be converted to strings in the browser's implementation when you assign to sessionStorage. If you evaluate against "true" or convert to boolean it will work fine.
https://code.google.com/p/sessionstorage/
http://www.w3schools.com/html/html5_webstorage.asp

Categories

Resources