Rahul
Rahul

Reputation: 111

How to get variable value in JavaScript on event?

(function(){
   $("#btn1").on("click",function(){
       var myval = 123;
       console.log(myval);
   });
   $("#btn2").on("click",function(){
       console.log(myval);
   });
})();

How to get the value of myval on #btn2 event. (Getting error Uncaught ReferenceError: myval is not defined)

Upvotes: 1

Views: 161

Answers (2)

Nishit Maheta
Nishit Maheta

Reputation: 6031

declare var myval out side click event function. to know more regarding variable scope in javascript you should read on w3schools

(function(){
  var myval;

 $("#btn1").on("click",function(){
      myval = 123;
      console.log(myval);
  });

  $("#btn2").on("click",function(){
      console.log(myval);
  });

 })();

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You need to declare myval in a shared scope, so that the variable can be made accessible from the second method.

In your current code the variable myval is local to the first callback where it is declared, so it won't live outside the scope of that function.

(function(){
   var myval;
   $("#btn1").on("click",function(){
       myval = 123;
       console.log(myval);
   });
   $("#btn2").on("click",function(){
       console.log(myval);
   });
})();

Demo: Fiddle

Upvotes: 2

Related Questions