0

In my application, originally those codes works:

var htm = "<div> My content </div>";   
$("#divprint").html(htm);
window.setTimeout('window.print()', 4000);

however, when I try to wrap it within an if statement, it won't print:

var canprint= $.cookie("actionprint");  
alert("I am outside " + canprint);
if(canprint == null){
    alert("I am inside");
    var htm = "<div> My content </div>";
    window.setTimeout('window.print()', 4000);
}

when I run this codes, I only got first alert: "I am outside null"

As javascript's scope is function level, I am wondering, why that if failed?

8
  • I don't see any function definition in your code. Btw, console.log(typeof canprint, canprint); Commented Jan 23, 2014 at 4:29
  • did you forget a double quotation mark on the declaration of variable htm? Commented Jan 23, 2014 at 4:31
  • Is your code missing the closing quotes like your post is? Commented Jan 23, 2014 at 4:31
  • 2
    $.cookie() for the props that don't exist returns undefined. Commented Jan 23, 2014 at 4:32
  • @BlackSheep - That i think is the actual reason Commented Jan 23, 2014 at 4:33

3 Answers 3

1

Can you try the if statement like,

if (!canprint)
Sign up to request clarification or add additional context in comments.

Comments

1

OK. As weird it is:

Firstly, I tried to print out:

  console.log(typeof canprint, canprint);

amazingly, result is:

string null

so, I changed to if condition to:

if(canprint == "null")

then it can goes inside that if.

Though this is working, does anyone who can explain what has happened? This is really out of my expedition.

Comments

0

Remove the quote and parenthesis from setTimeout function

window.setTimeout(window.print, 4000);

And use something like this: jQuery check if Cookie exists, if not create it

var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }

2 Comments

Although this is a reasonable suggestion, it isn't necessary; the original call will also work. It doesn't answer the question.
This doesn't seem right. It sets the cookie before checking if it's already set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.