I need this comparison in my javascript to work.
if ((q2 != '' && correct2 != 'True') || (q2 != '' && correct2 != 'true') || (q2 != '' && correct2 != 'false') || (q2 != '' && correct2 != 'False'))
{
alert("You must enter true or false.");
}
q2 and correct2 are textboxes and if q2 has something in it and correct2 doesn't equal true, True, false, or False then I want the message box pops up. My code is not working. If I put true or false in the blank the error message still shows up.
EDIT
I have found how to make it work. Instead of putting || between the comparisons I put && and it works perfectly.
To get the value of a text input, do something like
var q2Value = q2.value;
For the conditionals, || is or, not or, and everytime you do a comparison you need 2 values/variables
(correct2 !== 'True ) || (correct2 !== 'true')...
You can see I wrapped the comparisons in parenthesis so its perfectly clear what should be compared to what, even if it isn't strictly necessary.
Since you need q2 to be correct before comparing the other condition, you can use a nifty feature called short-circuiting. Basically, && only proceeds if the first comparison is truthy, so you would do
(qa2 !== '') && (the rest)
Note that if a user doesn't enter the value at all, when you get the value of the text field it will be undefined (I think), not '''. So you should really just do
qa2 && (...)
Basically null, undefined, and '' are all falsy in javascript, so if qa2 is any of those values, the second part of the and won't be processed.
This should work.
if ((q2 != '' && correct2 != 'True') || (q2 != '' && correct2 != 'true') || (q2 != '' && correct2 != 'false') || (q2 != '' && correct2 != 'False'))
{
alert("You must enter true or false.");
}
try this
if(q2 !== '' && !(correct2 == 'true') && !(correct2 == 'True') && !(correct2 == 'False') && !(correct2 == 'false'))
{
alert("You must enter true or false.")
};
Related
I am validating my time in this way
if (
timeInMins != 0 &&
timeInMins != "0" &&
timeInMins != undefined &&
timeInMins != "undefined" &&
timeInMins != null &&
timeInMins != "" &&
!isNaN(timeInMins)
) {
timeInMinsCumulative += parseFloat(timeInMins);
}
Is there any way to make this ugly if-check to sophisticated code?
There are 6 falsy values in javascript: undefined, null, NaN, 0, "" (empty string), and false of course.
So, you can just write
if (timeInMins && timeInMin !== '0') {
timeInMinsCumulative += parseFloat(timeInMins);
}
This uses the coercion behavior of JavaScript and the logical AND operator to simplify your code. The following is very nearly equivalent to your code, but it will also guard against the arguments false and 0n.
if (timeInMins &&
timeInMins !== '0' &&
timeInMins !== 'undefined') {
// whatever
}
Questions for you: do you really expect to ever get the string 'undefined' passed to you? Why do you want to guard against '0' being sent to parseFloat? Are you sure parseInt is not what you want?
It seems you want to check if timeInMins is precise Number type or not.
function isValidNumber(num) {
return typeof num === "number" && !isNaN(num);
}
console.log(isValidNumber(""));
console.log(isValidNumber(undefined));
console.log(isValidNumber(NaN));
console.log(isValidNumber("undefined"));
console.log(isValidNumber(true));
console.log(isValidNumber(false));
console.log(isValidNumber(0));
console.log(isValidNumber("0"));
console.log(isValidNumber(1.234));
I am wondering if it is correct to write in this way and am I using the brackets correctly?
*This is a code for a country redirects pop-up. The countryCode var is the country of the user (detected by API) while the localStorage.country is which country the user is in on the website.
Feel free to ignore the logic, I just need to know if IF Statement can be written in this way.
if((countryCode == 'sg/' && localStorage.country != "sg/") ||
(countryCode == 'ie/' && localStorage.country != "ie/") ||
(countryCode == 'my/' && localStorage.country != "my/")){
/** Country Redirect Pop Up **/
}
Yes, it is valid and could also be written this way:
let acceptedCountryCodes = ['sg/', 'ie/', 'my/'];
if(countryCode !== localStorage.country && acceptedCountryCodes.includes(countryCode)){
/** Country Redirect Pop Up **/
}
Sure, the code has no problem... It will check if 1st option OR 2nd option OR 3rd option is true
The code currently has no problem!
The wrapping brackets are NOT required in this case because AND(&&) operator has higher precedence than OR(||) operator.
Take a look at the following example:
false && true || false && true = false
The above example is similar to (false && true) || (false && true) which simplies to false || false therefore the final result is false.
I have the following code which is supposed to first check the navigator.platform, and if the user is coming to the page from a device other than an iPhone or iPad, redirect to the given page. However, it is currently redirecting iPad and iPhone devices to that page.
var param = document.location.search.split("?link=");
//IF DEVICE IS NOT IPHONE, REDIRECT USER TO OTHER PLATFORM PAGE
if (navigator.platform != 'iPhone' || navigator.platform != 'iPad')
{
window.location.replace("other-platform.html");
}
else if(param[1] === 'faq-link' && navigator.platform === 'iPhone' || 'iPad' )
{
window.location.replace("#");
}
else if (param[1] === 'footer-link' && navigator.platform === 'iPhone' || 'iPad')
{
window.location.replace("#");
}
else if(param[1] === 'share-page-A-getapp' && navigator.platform === 'iPhone' || 'iPad')
{
window.location.replace("#");
}
else if(param[1] === 'share-page-B-getapp' && navigator.platform === 'iPhone' || 'iPad')
{
window.location.replace("#");
}
else if(param[1] === 'share-page-C-getapp' && navigator.platform === 'iPhone' || 'iPad')
{
window.location.replace("#");
}
Think about the logic here:
if (navigator.platform != 'iPhone' || navigator.platform != 'iPad')
If navigator.platform is equal to "iPhone", then it's not equal to "iPad". If it is equal to "iPad", it's not equal to "iPhone". The if test is therefore always true because all strings are either not equal to "iPhone" or else not equal to "iPad".
The || should be &&.
Subsequently, your tests that involve 'iPhone' || 'iPad' are not doing what you think. Take the first one:
else if (param[1] === 'faq-link' && navigator.platform === 'iPhone' || 'iPad' )
We can add parentheses to show how JavaScript interprets the expression:
else if (((param[1] === 'faq-link') && (navigator.platform === 'iPhone')) || 'iPad' )
That is, it compares param[1] to the string "faq-link" first. If that succeeds, then it compares navigator.platform to the string "iPhone". If that also succeeds, then the test is true. However, if one of those two tests fails, the other side of the || operator is the string constant 'iPad', and that will always be interpreted as true. Thus, each one of those comparison clauses also has an always-true condition.
To fix those, all you need to do is get rid of the tests for "iPhone" and "iPad", because once you fix the very first test as described above, the other tests can safely assume that navigator.platform is either "iPhone" nor "iPad". So that test would be just:
else if (param[1] === 'faq-link')
There is an error on your if conditions, the last one:
For example,
(param[1] === 'faq-link' && navigator.platform === 'iPhone' || 'iPad')
should be
(param[1] === 'faq-link' && navigator.platform === 'iPhone' || navigator.platform === 'iPad').
Also best to group conditions with additional parentheses for clarity, i.e,
( (param[1] === 'faq-link') && (navigator.platform === 'iPhone') || (navigator.platform === 'iPad') )
look at this:
else if(param[1] === 'faq-link' && navigator.platform === 'iPhone' || 'iPad' )
will allways return true because 'iPad' is true.
change like that:
else if(param[1] === 'faq-link' && navigator.platform === 'iPhone' || navigator.platform ==='iPad' )
Not sure why this only seems to work with the response "yes"(or "Yes"/"YES") - any help would be appreciated. Pretty new to this!
var yesNo = window.prompt("Are you from Earth?");
var lowerYesNo = yesNo.toLowerCase();
while (lowerYesNo != ("yes" || "no")){
yesNo = window.prompt("Please answer with \"Yes\" or \"No\". Are you from Earth?");
lowerYesNo = yesNo.toLowerCase();
}
switch (lowerYesNo){
case "yes":
window.alert("I thought so!");
break;
case "no":
window.alert("Capture the alien!!!");
break;
default:
window.alert("I don't know how you got this to display!");
}
"yes" || "no"
returns "yes", because it is a "truthy" value and therefore the first operand of || is returned.
If you want to compare to both values, you will need to split this into two separate comparisons:
while (lowerYesNo != "yes" && lowerYesNo != "no")) {
//...
The correct way to write that is
while (lowerYesNo !== 'yes' && lowerYesNo !== 'no') {
// ...
}
you can try this,
((lowerYesNo != "yes") && (lowerYesNo != "no")){
what you probably wanted to do was:
while (!(lowerYesNo == "yes" || lowerYesNo == "no")){
...
that's same as
while (lowerYesNo != "yes" && lowerYesNo != "no"){
...
Meanwhile, take note:
(x || y) // this expression will return x, if x is truthy otherwise y
and
(x && y) // this expression will return x, if x is falsy, otherwise it returns y
Hence the loop in your question is equivalent to this:
while (lowerYesNo != "yes"){
... // you must say "yes" else you're stuck in here.
}
Yes it can be but it needs to be a whole expression
while( expression1 || expression2)
So in your case it would be
while (lowerYesNo != "yes" || lowerYesNo != "no")
though as has been pointed out in this instance you probably want to use an &&, since you are trying to print the message only if it is (NOT yes AND NOT No)
Because evaluation of the expression
"yes" || "no"
results in
"yes"
according to javascript rules in evaluating the "or" operator.
I'm having web seminars for learning JS and we 're asked to create a simple Form. Now we need to check if an input text-box is empty or it has only white spaces.
Here is the Lab Solution:
if (firstTextBoxContent != "" && firstTextBoxContent != null)
while this is the solution it worked for me:
if (/\S/.test(firstTextBoxContent))
Is my way good enough to stick with it and why Tutor's way didn't work at all?
The lab solution is bad, as it first checks if firstTextBoxContent is empty, and then checks if it is null/undefined.
If it is undefined, the first check will result in a reference error and should therefore be in the reverse order.
However, the lab solution doesn't check for whitespaces.
Your solution won't work if firstTextBoxContent is undefined, so if there's a possibility for that, make sure to check like so:
firstTextBoxContent != null && /\S/.test(firstTextBoxContent)
some tests:
> firstTextBoxContent = undefined
> firstTextBoxContent != null && /\S/.test(firstTextBoxContent)
false
> firstTextBoxContent = null
> firstTextBoxContent != null && /\S/.test(firstTextBoxContent)
false
> firstTextBoxContent = ''
> firstTextBoxContent != null && /\S/.test(firstTextBoxContent)
false
> firstTextBoxContent = ' '
> firstTextBoxContent != null && /\S/.test(firstTextBoxContent)
false
> firstTextBoxContent = ' b'
> firstTextBoxContent != null && /\S/.test(firstTextBoxContent)
true
Another way to do this is
firstTextBoxContent != null && firstTextBoxContent.trim() !== ''
to avoid this wisdom:
You have a problem. You try to solve it with regex. Now you have two problems.