Combine && and || on javascript - javascript

I wish to say if URL has 'admin/deals' and 'edit' at the same time in the current url page OR if it contains 'deals/new', then DO something.
if ( (window.location.href.indexOf('admin/deals') > -1)
&& (window.location.href.indexOf('edit') > -1) ) )
|| if (window.location.href.indexOf('deals/new') > -1){
alert("your url contains the name franky");
}
But I get the following error:
SyntaxError: expected expression, got ')'

the syntax is:
if (condition) || (condition)
^---no "if" here
so
if ((a && b) || (c && d)) { ... }

You can't have an if expression inside of another if expression. Try this:
if ((window.location.href.indexOf('admin/deals') > -1 && window.location.href.indexOf('edit') > -1) || (window.location.href.indexOf('deals/new') > -1)){
alert("your url contains the name franky");
}

You don't need two if's - you just combine all your conditions into one if and add as many && and || as you need.
You should also ensure for every open ( there is a closing )
if (window.location.href.indexOf('admin/deals') > -1 &&
window.location.href.indexOf('edit') > -1 ||
window.location.href.indexOf('deals/new') > -1) {
alert("your url contains the name franky");
}
And you might want to introduce a variable for window.location.href
like var currentLocation = window.location.href;
and then use that variable ...

Related

How to check if the URL contains a number? [duplicate]

This question already has answers here:
Check whether an input string contains a number in javascript
(14 answers)
Closed 2 years ago.
I am using window.location.href.indexOf to check if URL contains a string and works very well for something like this:
if (window.location.href.indexOf("franky") > -1) {
alert("your url contains the name franky");
But it doesn't work to check if URL contains any number.
The following always calls the alert, even if no number is in the URL.
if (
window.location.href.indexOf("0") === -1 ||
window.location.href.indexOf("1") === -1 ||
window.location.href.indexOf("2") === -1 ||
window.location.href.indexOf("3") === -1 ||
window.location.href.indexOf("4") === -1 ||
window.location.href.indexOf("5") === -1 ||
window.location.href.indexOf("6") === -1 ||
window.location.href.indexOf("7") === -1 ||
window.location.href.indexOf("8") === -1 ||
window.location.href.indexOf("9") === -1
)
{ alert("false"); }
As gaetanoM suggested, a regular expression would be the easiest way to do it.
if (window.location.href.match(/\d/)) {
alert('contains a number');
} else {
alert('does not contain a number');
}

Check if a getElementById is empty

I have a if else function in javascript:
if(document.getElementById('lengthFront').value > 4 && document.getElementById('lengthFront').value < 296 && document.getElementById('lengthBack').value > 4 && document.getElementById('lengthBack').value < 296)
{
document.getElementById('param_length').classList.remove('bg-danger');
}
else
{
document.getElementById('param_length').className = "bg-danger";
}
Bu I need an extra check so it won't be executed when lengthFront or lengthBack is empty, I have tried different solutions but I can't find the right way to get it working. All my solutions are pointing to else
I have tried to add:
document.getElementById('lengthFront') == '' && document.getElementById('lengthBack') == '' &&......
document.getElementById('lengthFront') == false && document.getElementById('lengthBack') == false &&......
document.getElementById('lengthFront') == null && document.getElementById('lengthBack') == null &&......
document.getElementById('lengthFront') =!= undefined && document.getElementById('lengthBack') != undefined &&......
Any suggestions
if(document.getElementById('lengthFront') && document.getElementById('lengthFront').value != '')
First condition makes sure that the element exists, second one makes sure it's value is not empty.
For the most concise and readable approach to dealing with DOM elements that may or may not exist and that may not have a valid value if they do exist, might I suggest you leverage two friends: logical AND && which you can use as a faux null coalescing operator, and the 'conditional ternary' operator ?: in such a way that you can check for null and blank string, and then assign a default value (0) or the element value, all in the initial assignment statement. Also, you'll want to avoid multiple redundant getElementByXXX queries by simply assigning the result to a variable (better readability, less typing, performs faster):
var lengthFront = document.getElementById('lengthFront');
var lengthBack = document.getElementById('lengthBack');
var paramLength = document.getElementById('param_length');
lengthFront = (lengthFront && lengthFront.value != '') ? lengthFront .value : 0 ;
lengthBack = (lengthBack && lengthBack.value != '') ? lengthBack .value : 0 ;
if(lengthFront > 4 && lengthFront < 296 && lengthBack > 4 && lengthBack < 296) {
paramLength && paramLength.classList.remove('bg-danger')
} else {
paramLength && (paramLength.className = "bg-danger");
}

Adding the OR operator to a quizz form makes it accept any answers

I'm having a weird problem when trying to create a question form that is validated with Javascript:
If I write my validation like this:
if (typedValue === "myAnswer" && clearedLevels === 1){doStuff}
Everything works. But I want to create several correct answers, so I write:
if (typedValue === "myAnswer"||"secondAnswer" && clearedLevels === 1){doStuff}
..and all of a sudden anything written to the input form is accepted as the answer.
A correct way of writing it is :
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") && clearedLevels === 1) { doStuff() }
You cannot combine the condition (x === y || x === z) as x === y || z and expect the same results.
Any non-empty string in Javascript is true (yes, even the string "false"). Since "secondAnswer isn't empty, it's evaluated as true, and ORed with any other condition will result in true.
You are missing a comparison of typedValue to this literal, and presumably, brackets around the typedValue comparisons, since && has higher precedence than ||:
if ((typedValue === "myAnswer" || typedValue === "secondAnswer") &&
clearedLevels === 1) {
// doStuff
}
extending Akash Pradhan answer you could write
if (typedValue == "myAnswer" || typedValue == "secondAnswer" && clearedLevels == 1) { doStuff() }
but since the && has precedence over the || operator it would evaluate
if (typedValue == "myAnswer" || (typedValue == "secondAnswer" && clearedLevels == 1)) { doStuff() }

Multiple OR Strings

I cannot find out how to pass multiple strings in an If statement.
Here is my Code :
var date = new Date();
if (document.getElementById("postcode-entry").value == ("G74" || "G75")) {
if (date.getHours() < 8 ) {
window.alert("Sorry we are not open at the moment, please try again later.");
} else {
window.open("http://http://stackoverflow.com");
}
} else {
window.alert("Sorry we do not Delivery to your area, please collect from store");
}
How can i do this ?
The phrase ("G74" || "G75") forces a boolean evaluation on each string, and both will return true always.
So you would need to do something like this:
var myvar = document.getElementById("postcode-entry").value;
if(myvar === "G74" || myvar === "G75")
i am not sure if you want to follow this approach but try using the following-
var strArr = [ 'G74', 'G75' ];
if( strArr.indexOf( document.getElementById("postcode-entry").value ) !== -1 ) {
// Your normal code goes here
}
Using this, you can have n number of string tested in a single statement inside if.
This should do
var post_code = document.getElementById("postcode-entry").value;
if (post_code == "G74" || post_code == "G75")
I have never seen this before. Perhaps you can use the switch statement
But in your case I would recomment the following:
var poscode = document.getElementById("postcode-entry").value
if (postcode === "G74" || postcode === "G75") ......

Javascript - How can I check to see if a url is loosely equal to the one in the location bar?

function isSameUrl(url){ /*what goes here?*/ }
If the current url is http://www.example.com/test#bar, the following would return true:
isSameUrl('#bar')
isSameUrl('/test#bar')
isSameUrl('http://www.example.com/test#bar')
Basically, if the location bar would not change if a link with the specified url was clicked, then it should return true.
You need to parse the URI reference before comparing it. You can use this regular expression to parse URI references (slightly modified):
/^([^:\/?#]+:)?(?:\/\/([^\/?#]+))?([^?#]+)?(\?[^#]*)?(#.*)?/
Then you can compare each component that is not undefined to the corresponding component in the location object:
function isSameUrl(url, location) {
location = location || document.location;
var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]+))?([^?#]+)?(\?[^#]*)?(#.*)?/);
if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return false;
if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"),"") !== location.host) return false;
if (typeof match[3] === "string" && match[3].length > 0 && match[3] !== location.pathname) return false;
if (typeof match[4] === "string" && match[4].length > 0 && match[4] !== location.search) return false;
if (typeof match[5] === "string" && match[5].length > 0 && match[5] !== location.hash) return false;
return true;
}
For an exact match
var isSameUrl = function(url) {
return window.location.href == url;
}
and for your needs
changed for query string support
var isSameUrl = function(url) {
var path = function(s) { return s.replace(/\?.*$/,''); };
return path(window.location.href) == url ||
path(window.location.pathname + window.location.hash) == url ||
window.location.hash == url;
}
In modern browsers, the value of the location bar is stored in a Location object which you can access using the window.location property. It has various conveniences for accessing various parts of the URL, but the portion of the URL after the domain name can be found in: window.location.pathname. The portion after # can be found in window.location.hash (but only in the most recent browsers). The portion after ? can be found in window.location.search -- and so on.
If you want to see if a string is included in your URL, you can use this:
function isSameUrl(test) {
return window.location.href.indexOf(test) != -1;
}
I think isSame (url) would be something like this:
function isSame(url){
return window.location.indexOf(url) > 0
}
You need to build a regular expression based off 'url' parameter of your function, then test the current url against that regular expression. See http://www.w3schools.com/jsref/jsref_obj_regexp.asp for the details on creating the regular expression and on using the test() method to check for matches. There are many good regular expression testers online as well.

Categories

Resources