I have an If statement that runs within a 'for' loop to create markers for a Google map. Basically if a tick box is not ticked it runs the code all displays all markers, but if a checkbox is ticked then it checks for a 2nd parameter and only runs the code for the items that match this condition.
The code I have below works fine, but it means I have to use the same code in both parts of the if statement. Apart from building it into a function if there a better way of structuring the If statement to achieve this?
if(!FriendlyChecked){
//Code here
} else if(FriendlyChecked && Friendly == "Yes"){
//Same code here
}
If FriendlyChecked is false, the first condition is satisfied and the code will be executed.
Thus, if the second condition is reached, FriendlyChecked must be true, so you don't need to check it at all, you only need to check that Friendly == "Yes".
if(!FriendlyChecked || Friendly == "Yes"){
// code here
}
if( !FriendlyChecked || (FriendlyChecked && Friendly == "Yes") ) {
// your code
}
!FriendlyChecked || (FriendlyChecked && Friendly == "Yes") will check for either FriendlyChecked is false (not checked)
OR FriendlyChecked is true an value of Friendly is Yes
This will solve your problem
if((!FriendlyChecked) ||((FriendlyChecked)&&(Friendly == "Yes")){
//Code here
}
Related
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
}
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")))
This should be simple but I can't get it to work. I am attempting to check if the value of a hidden input is empty on focus of a textarea in the same form. I don't understand why this does not alert() my message when empty:
$("#postbody").focus(function() {
var inputLength = $("#topicCategory").val().length;
console.log(inputLength);// outputs 0
if( inputLength == 0 ) {// condition is true, but code does not run.
alert("Please select a category to post your question in.");
}
});
Am I missing something here?
I have also tried all sorts of other ways with no luck.
I tried your conditional statement and it does work.
Since you are expecting a zero, instead of using double equals to check against zero you can use the NOT operator since zero evaluates as falsy.
if (!inputLength) {// condition is true, but code does not run.
console.log("Please select a category to post your question in.");
}
Truthy and Falsy: When All is Not Equal in JavaScript
You are attaching onfocus handler function for the textarea postbody before it is created in DOM. You have to attach the handler function inside JQuery.ready() function which ensures the code inside it is executed after the DOM is ready.
$(document).ready(function(){
$("#postbody").focus(function () {
var inputLength = $("#topicCategory").val().length;
console.log(inputLength);// outputs 0
if( inputLength == 0 ) {// condition is true, but code does not run.
alert("Please select a category to post your question in.");
}
});
});
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.
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