Why is my criteria inside IF not working? - javascript

Even though I enter the exact same input as the criteria, the code still doesn't run properly.
--> Link to the CodePen of this error <--
let addOrRem = String(prompt("Do you want to add or remove any content? (add/rem)").trim().toLocaleLowerCase());
if(addOrRem !== "rem" || addOrRem !== "add") {
alert("Invalid answer, try again!");
}
If I write the exact same code in a bundled way, the criteria works properly...
--> Link to the CodePen of this error partially solved <--
let addOrRem = String(prompt("Do you want to add or remove any content? (add/rem)").trim().toLocaleLowerCase());
if(addOrRem !== "rem") {
if(addOrRem !== "add"){
alert("Invalid answer, try again!");
}
}
I was expecting the first code to give the exact same output as the second one. I tried switching it for function "while" but resulted in the same issue.

That's because your condition should actually be an AND, not an OR.
if (addOrRem !== "rem" && addOrRem !== "add")
Consider the fact that addOrRem can only be equal to one value, so one of addOrRem !== "rem" and addOrRem !== "add" will always be true (and thus the entire condition will always be true with ||). addOrRem cannot be simultaneously equal to both "rem" and "add", which is required for your original condition to be false.

Related

Javascript stops when first if condition fails, need to move it to second condition

I have the following code in which I ask it to check if either one of 2 dataLayer values is "!= false" then run the rest of the code.
However, code breaks as soon as the first condition fails and does not move to check the second condition. So, how can I let both conditions be checked as one of them will always be available in dataLayer?
function init() {
if (dataLayer.condition[1] != false || dataLayer.condition[2] != false) {
Do something
}
}
Below is the screenshot of the error I get when the first condition values are missing on the page.
You can use optional chaining (?.) for this, if your execution context is expected to support it:
if (dataLayer?.condition[1] != false || dataLayer?.condition[2] != false) {
// Do something
}

JavaScript syntax for multiple condition checking

I want to write a JS condition to disable the save button for the following condition;
if status is CLOSED OR
if my model does not have BOTH UPDATE_GLOBAL and UPDATE_LOCAL privilege
I have written the following code;
if ((self.model.get("status") === "CLOSED") || (!self.model.hasPrivilege("UPDATE_GLOBAL") && !self.model.hasPrivilege("UPDATE_LOCAL"))) {
$("#save").attr("disabled", true);
}
Is this the best optimized code? Also are there any unnecessary parentheses (which always confuses me)?
You've said
if my model does not have BOTH UPDATE_GLOBAL and UPDATE_LOCAL privilege
...but that's not what that part of the condition is checking. It's checking if you don't have both; if you have just one, the check result is incorrect.
If you want the button disabled for status = CLOSED or your model doesn't have both privileges, then:
if (self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL"))) {
$("#save").attr("disabled", true);
}
Also are there any unnecessary parentheses (which always confuses me!!)
Yes, you don't need the parens around self.model.get("status") === "CLOSED" (but they're harmless).
Also note that your code never enables the button, it just disables it or leaves it alone. If you also want to enable it when the condition for disabling isn't true, then:
$("#save").attr("disabled", self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL")));
or (easier to debug):
var flag = self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL"));
$("#save").attr("disabled", flag);
I would put it like that:
if (self.model.get("status") === "CLOSED" || !(self.model.hasPrivilege("UPDATE_GLOBAL") && self.model.hasPrivilege("UPDATE_LOCAL")))

Checking if undefined in jQuery/Javascript

I have the following:
var currentQuestion = $(this).closest(".question")
I have tried everything suggested in this, this and this question:
if(currentQuestion !== undefined)
if(currentQuestion !== "undefined")
if(typeof currentQuestion !== undefined)
if(typeof currentQuestion !== "undefined")
if(currentQuestion !== null)
if(currentQuestion != undefined)
if(currentQuestion != "undefined")
if(currentQuestion.data("index") !== null)
if(currentQuestion.data("index") !== undefined)
if(typeof currentQuestion.data("index") !== undefined)
But it keeps going inside the if statement...
I have this inside the if:
console.log("nextQ: " + currentQuestion.data("index"));
and nextQ: undefined is getting print out
any other ideas?
EDIT:
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the one similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.
The result will never be undefined, it's always a jQuery object. If the operation didn't find any elements, the jQuery object will be empty, so you check how many element there are in it to see if found anything:
if (currentQuestion.length > 0)
After you have checked that there is actually any element in the jQuery object, you can check if there is any data associated to the element.
If no data is associated with an element, the data method will return undefined when you try to read the value. So, to check if there is no data, you should check the type of the value that the data method returns:
if (typeof currentQuestion.data("index") != "undefined")
If you want to check any elements exist, then check the length.
var currentQuestion = $(this).closest(".question");
if (currentQuestion.length > 0) {
console.log("nextQ: " + currentQuestion.data("index"));
}
if (currentQuestion.length) {
Should work fine. If it goes in there, it found something. And instead of looking at the if statement you need to look at your html and see what it found.
What you want is currentQuestion.length.
jQuery selectors return an array of elements matching the selector. To test for values in an array, you should use length:
Boolean([].length); //false
Because 0 evaluates to false, you can just use if (currentQuestion.length).
If you're trying to check for it when it is false, use !:
if (!currentQuestion.length)
For your question of why != worked but not !==, I would suggest this question: Difference between == and === in JavaScript
Basically, currentQuestion.data('index') is not strictly equal to null, but it could evaluate to null: same as [] == 0 evaluates to true, but [] === 0 evaluates to false.
It is probably not the most elegant solution. But somehow
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the most similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.

javascript if condition && condition doesn't work

the AND && operator doesn't work, but when i replace it with an OR || operation it is workin, why? I just used OR || operator for testing, what i need is an && operator.
Please help. thanks
function validate() {
if ((document.form.option.value == 1) && (document.form.des.value == '')) {
alert("Please complete the form!");
return false
} else return true;
}
i also tried nested if but it doesn't work too
if(document.form.option.value==1)
{
if(document.form.des.value=='')
{
alert ("Please complete the form!");
return false
}
}
It sounds like || is what you are looking for here. The && operator is only true if both the left and right side of the && are true. In this case you appear to want to display the message if the value is 1 or empty. This is exactly what the || operator is for. It is true if either the left or right is true
If Or operator is working, means there are some javascript errors in your second part of condition. check document.form.des.value=='' (maybe just open your javascript console in Chrome/Firefox/IE8+)
its because one of the conditions specified above returns false and loop breaks. Is you use OR ,only one must be validated and returns true.. check your code for both the conditions.

Javascript only checks one field

Ok so I've been stumped on this one for days and its frustrating me. (Will frustrate me even more if it's something simple I'm overlooking).
I have a form generated in PHP which I want to verify that certain pieces are filled out. I do this via a JavaScript check when the user clicks the submit button.The JavaScript code is below:
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value == '' || document.getElementById('uname').value == ''
|| document.getElementById('sdescription').value == '' || document.getElementById('email').value == ''
|| document.getElementById('platf').value == "Select Group" || document.getElementByID('cate').value == "Select Category" )
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
For some reason though this only checks the ldescription field. If that field has text but all the others are empty it carries on like everything was filled out. Also if I change the order of my checks and ldescription is anywhere but the first check, it will do no check whatsoever even when all the fields are empty.
Any ideas?
EDIT:
Got it fixed. Along with the suggestion I marked as correct the document.getElementById('item').value command worked with only textarea boxes but not regular text input boxes. By changing the command to document.MyForm.myTextName.value everything fell into place.
Couple of problems i noticed with your sample code.
The last getElementById call has improper casing. The final d is capitalized and it shouldn't be
Comparing the value to a string literal should be done by === not ==.
JSLint complains there are line break issues in your if statement by having the line begin with || instead of having the previous line end with ||.
The first and third items are most likely the ones causing your problem.
Inside your if condition, when you are breaking a line, make sure that the last token in the line is the OR operator ||.
Javascript does semicolon insertion, so it may be that semicolons are being inserted (automatically, invisibly, by the interpreter) in a bad place.
Try the below code
<script language="JavaScript">
function checkFields()
{
if (document.getElementById('ldescription').value === '' ||
document.getElementById('uname').value === '' ||
document.getElementById('sdescription').value === '' ||
document.getElementById('email').value === '' ||
document.getElementById('platf').value === "Select Group" ||
document.getElementById('cate').value === "Select Category")
{
alert("Please fill out all of the starred (*) items" );
return false;
}
}
</script>
Please use Javascript && operator which returns true if both the elements are true. || operator evaluates to true in case atleast one of the element is true which is what is happening in your case. You can take a look at Javascript boolean Logic

Categories

Resources