tags:

views:

47

answers:

3

I am trying to get a page to display specific properties depending on whether or not a specific cookie is set... I am trying this

 var x = readCookie('age');
window.onload=function(){
if (x='null')  {    
      document.getElementById('wtf').innerHTML = ""; 
   };
if (x='over13')  {    
      document.getElementById('wtf').innerHTML = ""; 
   };
if (x='not13')  {    
   document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>"; 
   };

   }

It always just defaults to whatever is in the first if statement... I am still learning my javaScript so I am sure this is sloppy.. can someone please help me get this working?

A: 
 var x = readCookie('age');
window.onload=function(){
if (x==='null')  {    
      document.getElementById('wtf').innerHTML = ""; 
   };
if (x==='over13')  {    
      document.getElementById('wtf').innerHTML = ""; 
   };
if (x==='not13')  {    
   document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>"; 
   };

   }
Darin Dimitrov
A: 

this should be

if (x=='null')  {    
Salil
`if (x === 'null')` is *not* `if (x === null)`(and I even ran a test to verify it)
Stephen P
+4  A: 

In Javascript, = is an assignment operator (it sets the variable on the left to the value on the right). You want ==, which is the loose equality operator (although you could also use ===, which is the strict equality operator, for the actual example you gave).

For that specific situation, you might also consider using a switch instead:

var x = readCookie('age');
window.onload = function(){

    switch (x)
    {
        case null: // Or 'null' if you really meant the string 'null', but I suspect you meant null (not as a string)
            document.getElementById('wtf').innerHTML = "";
            break;
        case 'over13':
            document.getElementById('wtf').innerHTML = "";
            break;
        case 'not13':
            document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
            break;
    }
}

(You also might want to deal with the situation of the value not being any of the three things you're expecting.)

T.J. Crowder
ahhh yes.. i have learned that many times now.. eventually it will stick :P Thanks!!
zac