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?

codingrose
  • 15,563
  • 11
  • 39
  • 58
JavaScripter
  • 4,282
  • 9
  • 37
  • 45

3 Answers3

1

Can you try the if statement like,

if (!canprint)
vasudevanp
  • 215
  • 3
  • 8
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.

JavaScripter
  • 4,282
  • 9
  • 37
  • 45
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
     }
Community
  • 1
  • 1
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Although this is a reasonable suggestion, it isn't necessary; the original call will also work. It doesn't answer the question. – Barmar Jan 23 '14 at 04:35
  • This doesn't seem right. It sets the cookie before checking if it's already set. – Barmar Jan 23 '14 at 04:40