If Statement not working with And (&&) Operator - javascript

I'm having a hard time writing up what seems should be a simple if statement! I need it to say if mod does not equal a, b, or c - then do this. Here is what I was trying but have been unsuccessful:
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
When I type this into my editor it says there is an error, specifically that "The entity name must immediately follow the '&' in the entity reference."
.. and is not working when I go to test.
Any help is appreciated!!
UPDATE:
The url: esber.squarespace.com
The full script:
<script type="text/javascript" src="/storage/scripts/sessvars.js"></script>
<script type="text/javascript">
<![CDATA[
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
]]>
</script>
I want every page in the site to automatically redirect on page load to the verify page, unless it is the verify page (/verify), the "You are not verified" page (/not-verified), or the login page (/login) -- unless the user already verified by setting the sessvars, then they can continue on to the homepage.
To test this I go to esber.squarespace.com and click on one the menu items at the right (this menu would eventually be hidden when I'm done with the page) -- when i try to go to another page without veriying my age first i should be redirected back to the /verify page but that isnt happening.
If i revise the script to:
<script type="text/javascript" src="/storage/scripts/sessvars.js"></script>
<script type="text/javascript">
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
</script>
then it works fine(?)

Try this:
// <![CDATA[
onload=function(){
sessvars.browserConfirmation?'none':'';
sessvars.ageConfirmation?'none':'';
};
var mod = Squarespace.Constants.CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
if(sessvars.ageConfirmation != "yes"){
window.location = "/verify/";
};
};
// ]]>
If this doesn't work, just leave the code there for a bit, so that we can debug it directly on your website

Wrap your script in a CDATA section.
<script type="text/javascript">
<![CDATA[
// script here
]]>
</script>

I tried the EXACT same code as yours and it works fine:
function doSomething() {alert("doing");}
var CURRENT_MODULE_ID = 5195103000;
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
It did 'doSomething'. When value is changed to 5195103, nothing happens which is correct
The editor aside, what's the script error when you run it and what's the browser you used? I suspect it could be an error elsewhere or perhaps related to CURRENT_MODULE_ID ?

Are you embedding this javascript in an xml document?
It sounds like the xml document is not well formed, perhaps because the & should be escaped as &
The javascript by itself looks fine too me
Try:
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
You'll find out that way whether the javasciprt needs to be escaped
Edit in response to comment:
Try the following:
<script type="text/javascript">
<![CDATA[
var mod = CURRENT_MODULE_ID;
if (mod != "5827289" && mod != "5195103" && mod != "5181422") {
doSomething();
}
]]>
</script>

It sounds like your editor just thinks you're working with an XML document. Have you tried actually running this in a browser? If so, does the browser also give an error?

Are you trying to compare the ID as a string or value? Did you try it without quotes?
var mod = CURRENT_MODULE_ID;
if (mod != 5827289 && mod != 5195103 && mod != 5181422) {
doSomething();
}
or another method would be to use match
var mod = CURRENT_MODULE_ID;
if (!mod.match("5827289|5195103|5181422")) {
doSomething();
}

I got this error within a script section in an XSL file.
Entity '&' not defined
I adapted the above answer within my script and it worked.
Note the CDATA section in the code segment below
<script>
var Quantity860=<xsl:value-of select="$QuantityOrdered_860" />;
var Quantity850=<xsl:value-of select="$QuantityOrdered_850" />;
var QuantityToReceive860=<xsl:value-of select="$QuantityLeftToReceive_860" />;
if(parseFloat(Quantity860.textContent) !== parseFloat(Quantity850.textContent) <![CDATA[ && ]]> parseFloat(QuantityToReceive860.textContent) !== parseFloat(Quantity850.textContent))
{
Quantity860.style.color="#FF6347";
Quantity850.style.color="#FF6347";
QuantityToReceive860.style.color="#FF6347";
}
</script>

just use != in comparison instead of == then && will work
if(val != "" && val != "") {
console.log("filled");
}else
{console.log("empty"); }

Related

My if/else is not working like it should [duplicate]

This question already has answers here:
JavaScript if "x = (a || b || c)" statement not working
(2 answers)
Closed 7 years ago.
My if else is not working like it should. I have 1 if 1 else if and 1 else. When the function runs it executes the if even if the condition is "false".
Here is the JavaScript:
function onSearch(){
var site;
document.getElementById('bar').value = site;
//These are not the actuall links since it's not the actuall code.
if (site === "Google" || "google"){
location.href = "http://www.google.com";
}
else if (site === "Youtube" || "youtube"){
location.href = "http://www.youtube.com";
}
else{
document.getElementById("SearchFail01").innerHTML =
"The country " + site + " does not exist";
}
<!-- Here is the HTML -->
<input type='search' id='bar' list='countries' placeholder='Search..'>
<p id="SearchFail01"></p>
In Javascript, a string in a conditional statement is considered True. The "||" operator won't work the way you're trying to make it work so you'll have to spell it out.
if (site === "Google" || site === "google"){
location.href = "http://www.google.com";
}
else if (site === "Youtube" || site === "youtube"){
location.href = "http://www.youtube.com";
}
else{
document.getElementById("SearchFail01").innerHTML =
"The country " + site + " does not exist";
}
edit:
I also noticed this line:
document.getElementById('bar').value = site;
should probably be flipped if you want to assign bar's value to site
site = document.getElementById('bar').value;
The double pipe doesn't work like you expect. This is how it is supposed to be used.
var foo = someVar || "foo"; not to be used inside an if like that
In your case you could simply lowercase the site and use a single ===
if (site.toLowerCase() === "google") {
location.href = "http://www.google.com";
}
You might also want to consider using a switch.
switch (site) {
case "Google":
case "google":
location.href = "http://www.google.com";
break;
case "Youtube":
case "youtube":
location.href = "http://www.youtube.com";
break;
default:
document.getElementById("SearchFail01").innerHTML = "The country " + site + " does not exist";
break;
}
I believe you have a logic problem if your if and your endif conditions.
When you have 2 or more conditions in JavaScript, separated with the OR (||), or AND (&&) operators you need to make the comparisons in each condition.
Instead of:
if (site === "Google" || "google"){
you have to write:
if (site === "Google" || site === "google"){
And instead of:
else if (site === "Youtube" || "youtube"){
you have to write:
else if (site === "Youtube" || site === "youtube"){
Hope this is helpful!
Cheers mate!

CodeMirror and Brackets, Custom Mode with CSS Quick Edit

I'm making a Adobe Brackets Extension to add support for Laravel Blade syntax highlight.
Blade is a template system that runs on top of HTML (more specifically a .php file), without my extension active I can do CTRL+E Quick Edit on a css rule name to quickly find that rule on the stlye.css file.
But when I activate the extension, the CTRL+E is not working anymore, but the HTML syntax is working perfectly.
I'm using overlay mode over text/html.
Here is the main.js extension code:
define(function (require, exports, module) {
'use strict';
var LanguageManager = brackets.getModule("language/LanguageManager");
CodeMirror.defineMode("laravelblade", function (config, parserConfig) {
var mustacheOverlay = {
token: function (stream, state) {
var ch;
//Highlight Comments {{-- --}}
if (stream.match("{{--")) {
while ((ch = stream.next()) != null)
if (ch == "}" && stream.next() == "}") break;
stream.eat("}");
return "comment";
}
//--
//Highlight {{ $var }})
if (stream.match("{{")) {
while ((ch = stream.next()) != null)
if (ch == "}" && stream.next() == "}") break;
stream.eat("}");
return "def";
}
//Highlight {% $var %} (Laravel 5)
else if (stream.match('{%')) {
while ((ch = stream.next()) != null)
if (ch == "%" && stream.next() == "}") break;
stream.eat("}");
return "def";
}
//Highlight {% $var %} (Laravel 5)
else if (stream.match('{%')) {
while ((ch = stream.next()) != null)
if (ch == "%" && stream.next() == "}") break;
stream.eat("}");
return "def";
}
//Return Null if no condition was met.
else if (stream.next() != null) {
return null;
}
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "php"), mustacheOverlay);
});
LanguageManager.defineLanguage("laravelblade", {
"name": "Laravel Blade",
"mode": "laravelblade",
"fileExtensions": ["blade.php"],
"blockComment": ["{{--", "--}}"]
});
});
The real question is:
How can I add support for Quick Edit on my custom mode and *blade.php files?
I think the problem is this part of your code:
else if (stream.next() != null) {
return null;
}
Looking at CodeMirror's overlay mode demo, it does something slightly different:
while (stream.next() != null && !stream.match("{{", false)) {}
return null;
Your code is returning null once for each ignored character, while the demo is only returning null once per contiguous chunk of ignored characters.
Returning separately for every character seems to make CodeMirror break up all of its normal tokens into separate one-char tokens, which the Brackets Quick Edit code can't recognize -- e.g. if your cursor is here - cl|ass - CodeMirror says it's in an attribute token where the name is just "l", while the Brackets code is looking attributes named "class".

GeoIP Redirect Loop - How to solve it?

I want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages ​​simply edit the following variables:
var defaultsLang are the languages ​​that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();

Why doesn't my if-else statement work?

Can anyone see why this does not work:
<script>
if (url==showbasket.html||order1.html||order2.html||order3.html||order4.html) {
document.write('<span style="font-family:lucida;font-size:10px;">Hello</span>');
} else {
document.write('<span style="font-family:lucida;font-size:30px;">Hello Hello</span>');
}
</script>
I´m trying to write a script that do this:
IF URL = 1.html or 2.html or 3.html or 4.html THEN
write option1
ELSE
write option2 (for all other URL´s)
if (url == "showbasket.html" || url == "order1.html" || url == "order2.html" || url == "order3.html" || url == "order4.html")
You have to do the check for each url and if it's a string use quotes
I don't think you got your if condition right:
if (url == showbasket.html || url == order1.html || ...
This code is valid, but it will not do what you want
if (url==showbasket.html||order1.html
"url==showbasket.html" checks if "url" is equal to the "html" attribute of object "showbasket". Since showbasket does not exist, your code will throw an exception.
"||order1.html" means the same, check if the "html" attribute of "order1" object is "true"
Like others have said, what you want to do is :
if ( url == "showbasket.html" || url == "order1.html"

javascript in jsf/icefaces

I have file with jspx extension i write javascript like
function isNumber(inputId){
var value = document.getElementById('mainForm:'+ inputId).value;
var s = value.length;
while(s >= 0){
var c = value.charAt(s);
if(c > "9"){
alert("Value must be digit");
document.getElementById('mainForm:'+ inputId).value = "";
document.getElementById('mainForm:'+ inputId).focus();
return false;
}
s --;
}
return true;
}
that work perfect but when i check if condition like if(c > "9" || c < "0") it will gives error like
com.sun.facelets.FaceletException: Error Parsing /WEB-INF/includes/templates/cc-classic-template.jspx: Error Traced[line: 386] The content of elements must consist of well-formed character data or markup.
After long observation i found that <(less than) sign will create problem.
Is JSF not support < sign ?
Enclose your Javascript in CDATA Sections:
<script language="javascript" type="text/javascript">
/* <![CDATA[ */
function isNumber(inputId){
var value = document.getElementById('mainForm:'+ inputId).value;
var s = value.length;
while(s >= 0){
var c = value.charAt(s);
if(c > "9"){
alert("Value must be digit");
document.getElementById('mainForm:'+ inputId).value = "";
document.getElementById('mainForm:'+ inputId).focus();
return false;
}
s --;
}
return true;
}
//Code containing "<" also comes in this section
/* ]]> */
</script>
As explained by Matt Handy, you could not use the < or > sign in your JSPX, as this is a XML format. You have three solutions regarding your problem:
Escape by using < or >.
Use <![CDATA[ ... ]]> to hold your JavaScript code in your page.
Set your JavaScript code in a separate .js file, and load it in your JSPX page.
Besides the escaping and CDATA answers:
If you want to check if a value is a number, there is a javascript built-in function for that: isNaN
Here is an example:
if (isNaN(document.getElementById('mainForm:'+ inputId).value))
{
alert("Please enter digits");
document.getElementById(obj).focus();
document.getElementById(obj).select();
return false;
}

Categories