Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  195] [ 3]  / answers: 1 / hits: 26005  / 11 Years ago, mon, october 7, 2013, 12:00:00

Here is my simple scenario. I have a variable defined inside the ready() function which assigns the first value.



I also have a function outside ready(). What I want to do is to use the changed variable inside my new function.



Here is my JavaScript code:



var myFunction = function() {
// I wanna change Vp value here and wanna
// use this function with the new value
Vp = new value;

myFunction2 ();
};

$(document).ready(function () {

var Vp = first value asign;
$('#btnAddCustomer').click(myFunction);

var myFunction2 = function() {
// I will use Vp variable here with new value
};
});

More From » jquery

 Answers
11

Discard the var statement. It assigned the value to a new local variable, instead of the global variable.



Here:



var Vp = first assigned value
var myFunction2;

var myFunction = function() {
// I wanna change Vp value here and wanna use this function with the new value

Vp = new value
myFunction2();

};

$(document).ready(function () {

Vp = first value asign;

$('#btnAddCustomer').click(myFunction);

myFunction2 = function() {

alert(Vp)

};

});


Fiddle: http://jsfiddle.net/XGGvv/10/



NOW THAT WORKS.



A nice reading on JS variable scopes: http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/


[#75182] Friday, October 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denzelc

Total Points: 637
Total Questions: 89
Total Answers: 88

Location: Liechtenstein
Member since Wed, Dec 8, 2021
2 Years ago
;