views:

134

answers:

4

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?

+11  A: 

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.

Jorge Israel Peña
That did it. Thanks for the rapid reply!
b. e. hollenbeck
+2  A: 

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.

fastcodejava
+3  A: 

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")

mfeingold
+2  A: 

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;
}
priyanka.sarkar