1
(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)

1
  • 1
    move the variable declaration from the function Commented Mar 12, 2015 at 6:34

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

still getting "undefined".
@Rahul you will get undefined if you click button 2 before button 1
@Rahul also don't forget to remove var from var myval = 123;
@Rahul try the attached fiddle - jsfiddle.net/arunpjohny/4fe21hcx/1 - try to recreate it there
1

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);
  });

 })();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.