Monday, July 30, 2012

javascript – How to correctly alert my variable



I have a pretty decent understanding of Jquery but decided to dig in inside JavaScript because I have no understanding of \”raw\” JavaScript.

So here\’s my problem: on document load my function executes fine and alerts: \’Hi my name is John\’ but on button click it alert\’s just :\’Hi my name is\’. My question is why is this happening and how can I solve it?

I know that I can FIX IT by putting my variable INSIDE my function, but is there a way to call my FIRST variable declared outside my function (variable just after script type)?


Fiddle here



My code:



<!DOCTYPE html>
<head>
<script type=\"text/javascript\">

//If I try to call this variable WILL NOT WORK:(

var name =\'John\'; <--SO HOW CAN I CALL THIS VARIABLE TO MY CLICK FUNCTION?-->

function displayName(name)
{
//If I put my variable like this WILL WORK fine...
//var name =\'John\';
alert(\'Hi I am \'+name);

}

//This function works on document load
//displayName(name);
</script>
</head>
<body>

<!--This doesn\'t work well if variable is OUTSIDE my function:(-->
<button type=\"button\" onclick=\"displayName(name)\">Display Name</button>
</body>
</html>






Rating: 1 out of 5 based on 3 ratings



The post javascript – How to correctly alert my variable appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/javascript-how-to-correctly-alert-my-variable.html

No comments:

Post a Comment