Javascript 'if' conditional not ... conditioning - javascript

I'm checking a number of 'read more' links on my blog, and either hiding the link (for the first two posts), or hiding the content and keeping the link. I'm running the links' id attributes through an if ... else statement that looks like so:
$(document).find('.contentclicker').each(function(){
var pt = $(this).parent().attr('id');
if (pt == "postnum1" || "postnum2"){
$(this).hide();
}
else{
$(this).next().hide();
}
});
Note: There's some jQuery in there, but it's not relevant. I know from debugging that the var pt is being set correctly to post_num_1, post_num_2, etc. - but when it evaluates post_num_3 and so on, it doesn't go to the else. I've tried == and ===, among other things, and I can't figure out what's wrong.
Any suggestions?

I am pretty sure you cannot do if (pt == "postnum1" || "postnum2") in javascript. Try if (pt == "postnum1" || pt == "postnum2"). Basically, even if the first conditional of pt == "postnum1" were false, it'd treat the second conditional as true which would avoid the else clause at the bottom. At least, that's what I think.
Sorry if I misunderstood your question.

JavaScript is not strictly typed, it means in particular that it gives you some leeway int your data types and always tries to coerce the expression value to the data type it thinks to be your intention.
In your if statement it tries co convert the part after || to boolean and result of conversion of "postnum2" is always true.
I think what you intended was (pt == "postnum1" || pt == "postnum2")

The second part of condition "postnum2" always evaluates to true. You have to convert condition to first answer. Also your post says post_num_1, post_num_2, etc, but you are checking for post_num1.

Instead of if (pt == "postnum1" || "postnum2")
try
if ((pt == "postnum1" ) || (pt == "postnum2"))
{
// something
}
Also you can do something in the switch case(as an alternative)
switch(pt)
{
case "postnum1":
case "postnum2" : $(this).hide(); break;
default: $(this).next().hide(); break;
}

Related

String includes with two statements

I have a form where one can enter info gain if the want to change anything. The data is taking from the API, this.company is JSON and this.company.name points to the company name.
I have a if else code that does something if the string starts with Be or Pe, first though I want to do something when it doesn't include any of those. But I can't seem to make it with two statements. Can't find any documentation on this what so ever.
Entire code is just two more if else based if it's Be or Pe. They do not affect this code, that works when company name matches any of those. Problem is when company name does not match any of those.
Can anyone help me out?
Tried this:
if (!this.company.name.includes("Be") || !this.company.name.includes("Pe")){
do something}
Also tried
if ((!this.company.name.includes("Be") || !this.company.name.includes("Pe"))){
do something}
Can't get it to work. Last resort is to change the if else and make a last else that will be fall back. But that will cause another problem when input isn't done at all.
Edit.
Seems I wasn't clear on the agenda and full code. I wanted to see if it's possible to have two statements, and use ! infront of them. Here's the full code.
if (this.company){
if (!this.company.name.includes("Be") || !this.company.name.includes("Pe")){
this.category = 0;
some code which will eliminate further questions in the form..
}
else if (this.company.name.includes("Be"){
this.category = 1;
some code ...
}
else if (this.company.name.includes("Pe"){
this.category = 2;
some code...
}
}
You have a minor logic problem here.
I think you wanna go for something like:
if (this.company.name && !(this.company.name.includes("Be") || this.company.name.includes("Pe"))){
That means when the company has a name and this name has no "Be" or "Pe" in the name. Remember if you wanna negate a statement you really have to negate the whole statement and not only parts of it or partwise.
(!A || !B) is not equal to !(A || B)
The first one means When A or B doesnt include "Be" and "Pe" - so far so good - but this statement is also true when only A doesn't include "Be" independent from what B is and it's also true when only B doesn't include "Pe" independent from A. On the upperhand the second one spoken means when A or B doesn't include "Be" and "Pe" - nothing else - You could also write something like (!A && !B) this is the same like !(A || B).
That means you could also go with:
if(!this.company.name.includes("Be") && !this.company.name.includes("Pe"))
A general mathematical overview about this topic would be "Boolean algebra".
Further you said when the name starts with "Be" or "Pe" in your suggestion with "include" these search strings can be anywhere in the String not only in the beginning.
The solution would be the startsWith method for strings:
this.company.name.startsWith("Pe")
Regarding to your update
Correct me if im wrong but I think "be" and "pe" is just the beginning and more categories planned.
Under this conditions i would think of something like this:
if (this.company)
switch(this.company.name.slice(0,2)){
case "Be": this.category = 2;break;
case "Pe": this.category = 1;break;
//possibly more conditions
default : this.category = 0;break; //when company name doesn't start with the cases before
}
In my personal point of view this is a bit more readable. But this depends on the amount of methods and things you wanna call if the conditions are true.
Just add an initial if/else statement to check if there is an input value or not and within the if statement, you can nest your second if/else statement for checking if the company name starts with "Be" or "Pe" using the startsWith() method.
if (this.company.name) { // checks if input has value or not
if (this.company.name.startsWith("Be") || this.company.name.startsWith("Pe")) {
[do something]
} else {
[no company which starts with Be or Pe. Do something else]
}
} else {
[no value was inputted. do something else]
}
Edit:
With regards to your updated question, you can just add a bang ! in the nested if statement and add the other if statements as required like this:
if (this.company.name) { // checks if input has value or not
if (!this.company.name.startsWith("Be") && !this.company.name.startsWith("Pe"))) {
this.category = 0;
} else
if (this.company.name.startsWith("Be")) {
this.category = 1;
} else
if (this.company.name.startsWith("Pe")) {
this.category = 2;
}
} else {
[no value was inputted. do something else]
}
You can use RegExp.test
if(/^(?:Pe|Be)/.test(this.company.name)) {
//starts with Pe or Be
} else {
}
If only care about the case when name does not include any of these
if(/^(?!Pe|Be)/.test(this.company.name)) {
//does not start with Pe or Be
}

JavaScript if else problems

everyone!
I have been having problems with my code. I think I know what is wrong but I can't seem to fix it, no matter how much I tried so I decided to take it up with the community. I think it is because of the second if statements contradict the one before it. Here, take a look.
if (Character.style.backgroundImage === "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/2.png)";
} else (Character.style.backgroundImage != "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/1.png)";
Hopefully, you see what I am talking about and know what the answer is. As I said in my last post I am not a great coder, so don't judge me too hard, XD.
There is no reason to repeat the conditional check negated with an else, that is only needed for an else if. Change
} else (Character.style.backgroundImage != "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/1.png)";
}
to something like
} else {
Character.style.backgroundImage =
"url(../images/animations/moveRightAnimation/1.png)";
}
Else doesn't take any parameters it's literally what runs in the case the if evaluates false.
If you want multiple exclusive if blocks, you need to use 'else if' where you currently have else
Syntax for if condition :
if ( condition ){
// code
}
else {
// code
}
Note : After else there cant't be any condition . Or you must use if-else.(Only if you want to use multiple conditions.And you seem to check only one,so its not needed.)
Syntax for if condition :
if ( condition ){
// code
}
else if ( condition ){
// code
}

How to user a condition in a String inside an IF sentence

I have the following situation:
var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";
The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:
if(condition)
//Do something
else
//Do something
Can I do that without using "eval()"? How? I want to avoid it:
if(eval(condition))
...
NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)
If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.
I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.
A bit confused..
But if the answer and isClosed set by the user.. then just something like this will suffice..
answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
//Do something
}
else{
//Do something
}

If input = "whatever", then show element and if not, show a different element

I've been trying to do this for about an hour now looking up codes but I just can't find out how to do this.
I need a kind of ask answer thing.
Lets say its like a quick math quiz and the question is "what's 2 plus 2?" and if the answer with 4, then a div would show after they click the button.
But if they answer with anything else, than a different element would show.
Here's what I have so far,
$(document).ready(function(){
$("button#try").click(function(){
if(!$('input#input1').val() = "4"){
$('#yeselement').show();
}
else {
$('#noelement').show();
}
});
});
but for me, it doesn't work. Is something wrong with the code? Am I doing it wrong?
You have to use != to compare:
if ( $('input#input1').val() != "4") {
// ^ you want to compare, not assign
Use == for comparisons. You also need a pair of parenthesis for grouping:
if ( !($('input#input1').val() == "4") )
You should better use !== or === in your condition:
if($('input#input1').val() !== "4") {
Note that == and != also work but are less safe than === and !==.
Source: Which equals operator (== vs ===) should be used in JavaScript comparisons?

If statement in jQuery plugin

I have a jQuery plugin with an if statement in it.
For some strange reason (probably it is just me screwing things up) it always gets in the else part even when the url's are the same.
if (opts.startUrl == track.permalink.url) {
var active = true;
} else {
alert('|'+opts.startUrl+'| |'+track.permalink_url+'|');
var active = false;
}
Check it out # http://dev.upcoming-djs.com
The surrounding code uses track.permalink_url, while the if block evaluates track.permalink.url (which is always undefined), so this condition:
opts.startUrl == track.permalink.url
Always evaluates to false
Update: as #brianpeiris points out, the correct fix here would be to change the condition to:
opts.startUrl == track.permalink_url
Start printing both the values and see what is the difference , otherwise do this
if (opts.startUrl.toLowerCase() == track.permalink.url.toLowerCase())

Categories