Reputation: 24213
Okay so i am using the following code.
<html>
<head>
<link type="text/css" rel="stylesheet" href="html.css" />
<script type="text/javascript">
function getName()
{
if(name)
alert("you thought i forgot you" + name + "?");
else
name=prompt("what's your name","here");
}
</script>
</head>
<body onload="var name;">
<p onclick="getName()"; >click here</p>
</body>
</html>
Now if on clicking the <p>
text first time it prompts me, and if I click cancel without entering my name, and then again click the <p>
text, it doesnt prompt me anything,
instead it shows the name to be filled as NULL. now in C
,
char a=NULL;
if(a)
evaluates to false, doesn't it happen in javascript?
Upvotes: 2
Views: 696
Reputation: 20205
<html>
<head>
<link type="text/css" rel="stylesheet" href="html.css" />
<script type="text/javascript">
var name;
function getName() {
console.log(name, typeof name);
if(name && name !== 'null') {
alert("you thought i forgot you" + name + "?");
} else {
name=prompt("what's your name","here");
}
}
</script>
</head>
<body>
<p onclick="getName()"; >click here</p>
</body>
</html>
As you can see from the console output, name is a string with value null. This is pretty stupid, but I guess window.name stringifies the value, in this case null.
EDIT:
You probably shouldn't be using the word name as it's reserved (used as a property in window).
window.name returns a string value of whatever is stored in it. For example:
window.name = null;
window.name === 'null'
true
window.name === null
false
Upvotes: 0
Reputation: 114461
This is a tricky situation.
The identifier "name" is special for the global window object so you cannot use it reliably as a variable.
Using for example name$
your code works as expected.
Also I think that "onload" requires an expression, not a statement; so you cannot use it that way. Apparently works with name
because that is predefined.
Upvotes: 1
Reputation: 25463
One thing you might be running into: when you set the global name
, you are actually setting window.name
. window.name
is a special property that actually persists even after refreshing the page.
Try making a page with the script:
alert(window.name);
name = 'hello';
On the first run, it should alert "undefined". If you refresh the page, though, you should see "hello".
You can avoid the problem by renaming name
to something else.
Upvotes: 4
Reputation: 6216
This fiddle behaves as you desire, I think: http://jsfiddle.net/YUCyL/5/
As you can see, I moved the variable declaration to the head and renamed it to username instead of "name".
Upvotes: 1
Reputation: 2082
try with this
if (name==undefined) name=prompt("what's your name","here"); else alert("you thought i forgot you" + name + "?");
Upvotes: 1