0

jquery

$(selector).on('click',function(){
var $myvar = 'hi';
});

alert($myvar); // this won't alert hi as this is out of click function

How can I call that $myvar outside the function?


Update

I tried with below answers but seems not working http://jsfiddle.net/G5vAv/1/

I would like to return the value 'hi' when alerting. Any idea?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

4 Answers4

0
var $myvar;
$(selector).on('click',function(){
   $myvar = 'hi';
});
alert($myvar);

By using var inside the click function you are setting $myvar as a local variable which is only accessible inside the click function.

To make your variable accessible outside you have to declare it outside.

More about it javascript-variable-scope

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

You have to declare the variable outside the function like so

var $myvar;
$(selector).on('click',function(){
    $myvar = 'hi';
});

alert($myvar);

This happens because of the different scopes in javascript, your variable was applied to the function's scope and the alert is outside that scope and therefore unable to access it.

All you have to remember is that javascript looks up for variables not down so you can only access variables that are declared on the current level or higher here is some examples.

var level_1;

// I can access level 1

function somefunc() {
   var level_2;
   // I can access levels 1 & 2


   return function() {
      var level_3;
      // I can access levels 1, 2 & 3 
   }
}
iConnor
  • 19,997
  • 14
  • 62
  • 97
  • @C-Link That's because the default value for a variable is `undefined` if you alert it after you click then you will see the value like this http://jsfiddle.net/G5vAv/2/ – iConnor Sep 12 '13 at 05:40
0

you can't, since you are setting $myvar inside the function, it is limited to the scope of that function. if you want to be able to access the variable outside of the function, you can either:

  1. leave out the var keyword, which will make it a global variable, or
  2. define it outside of the function:

var $myvar;
$(selector).on('click',function(){
    $myvar = 'hi';
});
iConnor
  • 19,997
  • 14
  • 62
  • 97
kennypu
  • 5,950
  • 2
  • 22
  • 28
0

You need to define the $myvar outside of the function

var $myvar;
$('#click').on('click',function(){
    $myvar = 'hi';
    checknow();
    return false;
});

function checknow()
{
    alert($myvar);
}

FIDDLE

Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63