If condition on windows load not working in javascript - javascript

The following code is not working and cant understand why. What am I doing wrong?
$(function() {
var advanced = localStorage['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")|(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});

Check the OR operator. It should be like -
if((advanced == "true")||(advanced==true)){

This expression is not working:
if((advanced == "true")|(advanced==true)){
It’s enough to do:
if(advanced) {
because "true" as a string is also "truthy".

You are missing an extra |:
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true") || (advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});

OR operator needs to be two |..Like this:
if((advanced == "true") || (advanced==true)){
If the variable advanced is a BOOLEAN, then you can simply use this:
if(advanced) {
// code here..
}

I think there is mistake in your javascript code.so you can not use "|" instead of "||"
so try by the following code gets solved your error.
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")||(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});

As you say that a proper OR operator is still not working, then I suspect it must be a problem with the case.
Check this fiddle: http://jsfiddle.net/VTfQU/
Use this code to simplify your if condition:
var advanced = localStorage.getItem['advanced-search'];
advanced = advanced.toString().toLowerCase();
if (advanced == "true") {
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = "false";
}
The idea is to convert your data into lowercase and then just check the condition on that value. I have added toString() just to be safe, anyway getting a value out of local storage will always be a string.

Related

simplify if else statement

I have some functionality dependent on many conditions. All variables in conditional statements are boolean variables and the code is the following and I don't like it:
if (userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Is there a way to make it more understandable and nice?
That's about as concise as you're going to get with JavaScript. I suppose if you really wanted to, you could create variables to store your binary options:
var multiMarketOneSelected = userHasMoreThanOneMarket && isOnlyMarketSelected;
var singleMarketMultiAgency = !userHasMoreThanOneMarket && userHasMoreThanOneAgency;
if (multiMarketOneSelected || singleMarketMultiAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Though I don't really know if you gain much readability from that.
Your code seems fine, but if you don't like it you could do something like this (note that the only improvement here is style, if you like it better):
function check(){
return {
valid: userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency,
case: [
isOnlyAgencySelected,
noAgencySelected && isOnlyMarketSelected
]
};
}
var conditions = check();
if (conditions.valid) {
if (conditions.case[0]) {
//do case 1
} else if (conditions.case[1]) {
//do case 2
}
}
Some things I would try to make the code more readable:
Initialise the variables in a way that you don't have to negate them again. So !userHasMoreThanOneMarket becomes userHasOneMarket
isOnlyMarketSelected sounds redundant to me. And you are checking it in the outer if-clause and the inner again.
You probably have a lot of code above this code snippet to initialise and set all this boolean values. Try return; statements after each variable to get rid of if-conditions.
I hope this helps.

Strange data-attribute boolean issue

I have a live -on click- event for a Header which has an arrow flipping up/down upon opening & closing it's contents.
The strangest thing is happening with ! followed by a variable -- which is supposed to flip it from true -> false, and vice versa. Basically it's not working at all, and it flips to false and stays there... Check out the fiddle to see what I mean.
I've deleted lots of code for the sake of brevity.
Demo Code
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).attr('data-state');
if (_state === 'true') {
// do stuff
}
else {
// do stuff
}
// This is where the issue is happening, it isn't flipping the Boolean value
// !"true" = false, !true = false, it works with strings or booleans
$(this).attr('data-state', !_state);
});​
I can get it working perfectly fine if I do the following:
if (_state === 'true') {
// Manually flip the data-state boolean
$(this).attr('data-state', false);
}
Is there something I'm missing why this isn't working the way it should ?? Just wondering why it's doing this!
I think you are trying to do this:
http://jsfiddle.net/JKUJb/2/
if so, the problem was that you are using .attr() which returns a string, so if you convert:
!"true" //false
!"false" //false
.data() on the other hand returns the value already "casted
EDIT:
Just to be more clear, in javascript the only falsy values are:
false;
null;
undefined;
'';
0;
NaN;
So if you really wanted to use .attr(), you could, but I recommend that first you do:
var _state = $(this).attr('data-state') === 'true'; //if 'true' then true, false otherwise
Good luck!
Change your second line to:
var _state = $(this).attr('data-state') == 'true';
And in the if statement check for boolean:
if ( _state ) {
// do stuff
...
_state is a String (typeof _state === String //true) you need to convert it to a boolean first
(a String will alwase be true)
If you really want to use data- attributes for this, use jQuery's .data method to retrieve and set the value. It will automatically convert the string "true" into a Boolean, or the string "1" into a number:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).data('state');
if (_state) {
// do something
}
$(this).data('state', !_state);
});​
http://jsfiddle.net/mblase75/JKUJb/6/
Or you could toggle a class -- you can use the .hasClass method to return a Boolean:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).hasClass('data-state');
if (_state) {
// do something
}
$(this).toggleClass('data-state');
});​
http://jsfiddle.net/mblase75/JKUJb/3/

check if html attribute exist and has right value with jquery

Is there a better way for checking an attribute for:
it exist. so value must be false if attribute doesn't exist
Value is correct (boolean)
var isOwner = false;
if ($(selectedItem).is('[data-isOwner="True"]') || $(selectedItem).is('[data-isOwner="true"]')) {
isOwner = true;
} else {
isOwner = false;
}
Now I need to check for 'True' and 'true'...
Thanks
You can convert the value stored in data-isOwner to lower case and only compare the value to 'true'.
if (($(selectedItem).attr ('data-isOwner') || '').toLowerCase () == 'true')
The above use of <wanted-value> || '' will make it so that if the selectedItem doesn't have the attribute data-isOwner the expression will result in an empty string, on which you can call toLowerCase without errors.
Without this little hack you'd have to manually check so that the attribute is indeed present, otherwise you'd run into a runtime-error when trying to call toLowerCase on an undefined object.
If you find the previously mentioned solution confusing you could use something as
var attr_value = $(selectedItem).attr ('data-isOwner');
if (typeof(attr_value) == 'string' && attr_value.toLowerCase () == 'true') {
...
}

How to change a javascript variable?

I'm trying to change a variable depending on what it's current value is:
window.addEventListener("popstate", function(e) {
if (direction === leftnav){
direction = rightnav
}
else{
direction = leftnav
};
loadPage(location.pathname);
});
this doesn't seem to work somehow :s
can someone help me with this?
Thanks in advance :)
EDIT: here is the full js file: http://pastebin.com/7zZseW74
EDIT 2: what seems to happen is that the loadPage function just does not seem to fire...
Try using == instead of ===:
if (direction == leftnav) {
direction = rightnav;
} else {
direction = leftnav;
}
Also, do include proper ; inside if and else clauses. You could also provide more information in order to get better help. Information like: what are leftnav and rightnav variables. If they are not variables but literals, you should enclose them within ". Like "rightnav" and "leftnav".
if (direction == leftnav){
^ requires only 2 '=' signs.
should be correct for the rest.
I believe all you're missing is semicolons.
if (direction == leftnav) {
direction = rightnav;
} else {
direction = leftnav;
}
Also, unnecessary ===
try this
if (direction == 'leftnav')
{direction = 'rightnav';}
else
{direction = 'leftnav';}
You haven't said a thing about leftnav and rightnav variable, so I suspect that you may want to use strings ('leftnav' and 'rightnav') instead, otherwise both are likely to be undefineds.
EDIT: Now that you posted the code, brief look at it suggests that yes, you wanted quoted strings.
window.addEventListener("popstate", function(e) {
direction = (direction=="leftnav")?"rightnav":"leftnav";
loadPage(location.pathname);
});

Javascript OR in an IF statement

I am trying to make an if statement in javascript that will do something if the variable does not equal one of a few different things. I have been trying many different variations of the OR operator, but I cant get it to work.
if(var != "One" || "Two" || "Three"){
// Do Something
}
Any ideas? Thanks!
Update:
I have tried this before:
if(var != "One" || var != "Two" || var != "Three"){
// Do Something
}
For some reason it does not work. My variable is pulling information from the DOM i dont know if that would effect this.
Actual Code
// Gets Value of the Field (Drop Down box)
var itemtype = document.forms[0].elements['itemtype' + i];
if(itemtype.value != "Silverware" || itemtype.value != "Gold Coins" || itemtype.value != "Silver Coins"){
// Do Something
}
Your expression is always true, you need:
if(!(myVar == "One" || myVar == "Two" || myVar == "Three")) {
// myVar is not One, Two or Three
}
Or:
if ((myVar != "One") && (myVar != "Two") && (myVar != "Three")) {
// myVar is not One, Two or Three
}
And, for shortness:
if (!/One|Two|Three/.test(myVar)) {
// myVar is not One, Two or Three
}
// Or:
if (!myVar.match("One|Two|Three")) {
// ...
}
More info:
De Morgan's Laws
Edit: If you go for the last approaches, since the code you posted seems to be part of a loop, I would recommend you to create the regular expression outside the loop, and use the RegExp.prototype.test method rather than String.prototype.match, also you might want to care about word boundaries, i.e. "noOne" will match "One" without them...
Assuming you mean "val does not equal One or Two or Three" then De Morgan's Theorem applies:
if ((val != "One") && (val != "Two") && (val != "Three")) {
// Do something...
}
For a shorter way to do it, try this format (copied from http://snook.ca/archives/javascript/testing_for_a_v):
if(name in {'bobby':'', 'sue':'','smith':''}) { ... }
or
function oc(a)
{
var o = {};
for(var i=0;i<a.length;i++)
{
o[a[i]]='';
}
return o;
}
if( name in oc(['bobby', 'sue','smith']) ) { ... }
The method mentioned by Mike will work fine for just 3 values, but if you want to extend it to n values, your if blocks will rapidly get ugly. Firefox 1.5+ and IE 8 have an Array.indexOf method you can use like so:
if(["One","Two","Test"].indexOf(myVar)!=-1)
{
//do stuff
}
To support this method on IE<=7, you could define a method called Array.hasElement() like so:
Array.prototype.hasElement = function hasElement(someElement)
{
for(var i=0;i<this.length;i++)
{
if(this[i]==someElement)
return true;
}
return false;
}
And then call it like so:
if(!["One","Two","Three"].hasElement(myVar))
{
//do stuff
}
Note: only tested in Firefox, where this works perfectly.
In addition to expanding the expression into three clauses, I think you'd better name your variable something other than var. In JavaScript, var is a keyword. Most browsers aren't going to alert you to this error.
Alternate way using an array:
var selected = ['Silverware', 'Gold Coins', 'Silver Coins'];
if ( selected.indexOf( el.value ) != -1 ) {
// do something if it *was* found in the array of strings.
}
Note: indexOf isnt a native method, grab the snippet here for IE:
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/IndexOf

Categories