This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 8 years ago.
$('#lobSelect').change(function () {
var selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});
console.log(selectedLob); //not available here
In the code above i'm using the variable selectedLob to store the value selected from dropdown.
how can i retrieve that value from outside the function?
Also say this function is stored in a file1.js - how can i access this variable from file2.js in a different folder.
Thanks
When you declare a variable, you make it local to the scope of the function it is declared within.
Declare it outside the function:
var selectedLob;
And don't re-declare it inside:
$('#lobSelect').change(function () {
selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});
It will still be undefined here:
console.log(selectedLob); //not available here
because it doesn't get a value assigned to it until the change event fires, but it will be accessible in the wider scope after that event has happened.
You can use global variable for your task, but this will lead to polluting the global namespace.
The good practise is to use application namespace instead of global namespace
Your file1.js
// your app namespace
var app = app || {};
// on document ready wrapper
$(function () {
$('#lobSelect').change(function () {
// initialize your variable at app namespace
app.selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
});
});
Your file2.js
// use the same app namespace or create it
// if not exist yet (in case when file2.js was loaded before file1.js)
var app = app || {};
$(function () {
// app.selectedLob is available here
});
var selectedLob is local to $('#lobSelect').change(function () { function not accessible outside
Solution
var selectedLob =''; //declare variable outside so it accessible
$('#lobSelect').change(function () {
//assign value here
selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});
console.log(selectedLob);
//it doesn't get the value as it runs before the change event fires so you get undefined value
Read What is the scope of variables in JavaScript?
you can also set a global variable inside a function using the following method
window["variableName"] = "some value";
then access it anywhere. for example:
console.log(window["variableName"]);
You can use jQuery.data function to store in $('#lobSelect')
$('#lobSelect').data("yourKey", yourVariable)
And retrieve like this:
var someVariable = $('#lobSelect').data("yourKey")
Or declare the variable outside the function as suggested if you want to use it right after (data will store for a longer time):
var selectedLob;
$('#lobSelect').change(function () {
selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});
console.log(selectedLob);
//accessible here,
//maybe not elsewhere in your code (depending on your code structure)
First problem you have here is the fact that you are using selectedLob variable outside of the scope it is defined in, so you have to move its declaration one level up so it can be used outside of the function as well (or even better you should restructure your code so this kind becomes unnecessary).
Second problem you have is you declare selectedLob variable inside change event handler and expect it to be defined immediately. To fix this (if you are using JQuery here) you can call your change handler function right after you declare it to initially kick start your variable initialization.
So in summary something like this:
var selectedLob =''; //declare variable outside change handler so it accessible
$('#lobSelect').change(function () {
//assign value here
selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
}).change(); // This will call your change event handler and hopefully init selectedLob
// Now selectedLob should be have value of selected option (if your DOM was ready...)
console.log(selectedLob);
And at the end I would have to say that you should really try to avoid things like this, try to restructure your JS code in a way that you maybe initialize all things you need in one place after DOM is ready and then to start up your app with some kind of init function passing all it needs or similar. Writing code like this will soon lead into one big pile of mess :)
Use global variable
var selectedLob; // use as a global variable to access outside of the function
$('#lobSelect').change(function () {
selectedLob = $('#mainWrapper').find('select[name="lob-select"] option:selected').val();
console.log(selectedLob); //prints to the console
});
if(selectedLob!=undefined){
console.log(selectedLob); //available here
}
Related
I have this code snippet.
var mapping = {};
_.each(labels,function(i,label){
debugger;
});
but mapping variable is not accessible inside the function.
I have a similar code somewhere else
var labels = {};
_.each(arrOfFields, function(element,index){
labels[prefix+element.fcnbb] = element.UI.label;
});
and labels is accessible here and i am able to use it.
Please explain me why does this happen ??
The problem here that mapping variable isn't declare within the function code block.
In debug mode if you used a callback function like in here you need to declare it within the function, so debugger will save it as his local variable.
so:
var mapping = {};
_.each(labels,function(i,label){
console.log(mapping); // here
debugger;
});
Just write variable name even in console.log() function, the debug will know his local variables, and then you will have an access to the variable itself.
I am working on a rating system and want to pull up each rating value by the jquery.
For this purpose I am doing like this, but I am unable to get previous event variable value into next event.
var r1Rating;
$(".rating-input").on("click",function(){
//alert($(this).attr("id"));
var r1=$(this).attr("id");
var r1Array=r1.split("-");
//alert(r1Array[r1Array.length-1]);
var r1Rating=parseInt(r1Array[r1Array.length-1]).toFixed(2);
$("#total_rating").html(r1Rating);
var r1Rating=r1Rating;
});
$(".rating-input1").on("click",function(){
alert(r1Rating); //I want to get value here
});
Any help, suggestion would be appreciated. Thanks
Even though you have a r1Rating in the external scope, since you are using var r1Rating in the click handler, you are creating a new locally scoped variable in the click handler. So any changes you make to the variable will be visible inside that method only and the variable in the external scope will not be updated.
var r1Rating;
$(".rating-input").on("click", function () {
//alert($(this).attr("id"));
var r1 = $(this).attr("id");
var r1Array = r1.split("-");
//should not use var here
r1Rating = parseInt(r1Array[r1Array.length - 1]).toFixed(2);
$("#total_rating").html(r1Rating);
});
$(".rating-input1").on("click", function () {
alert(r1Rating); //I want to get value here
});
The code below should be changes, since in this instance, you created a new r1Rating variable in a scope, which means that this was a different variable from the global one outside.
var r1Rating=r1Rating;
This should be changed to:
r1Rating=r1Rating;
So I am currently attempting to procedurally generate variable names based on some other things I want to do later in the function.
However when I attempt this as a trial function:
var gridCoord = [[1,2]];
var 'run' + gridCoord[0][0] + gridCoord[0][1] = function() {
console.log("Success!");
}
run12();
I am receiving syntax errors in the console.
You can't do it like that. Use dynamic naming of objects.
window['run'+gridCoord[0][0]+gridCoord[0][1]] = function() {
The window object is a global object; these functions can be called normally as any other global function can be called.
window['run'+gridCoord[0][0]+gridCoord[0][1] ]= function(){
console.log("Success!");
}
In the global scope, all variables are children of the window property
I am in a position where I need to "update" a function that exists in another javascript file. The file looks like this:
function jf(){
alert('1');
}
//call jf periodically
jf();
The second js file, which is loaded after looks like this:
console.log(jf);
console.log(window.jf);
var func=function(){
alert('2');
};
jf=func;
window.jf=func;
The first log successfully returns the original jf method, the second doesnt. The first set seems to set the local variable jf, and the second does basically nothing. Is there a way to achieve this functionality?
According to Javascript closures - behavior of overridden functions from the global scope
var done = and function done do basicaly the same thing. They will shadow the outer definition in the inner scope but they will not replace it on the outer scope.
This means you can only override your initial definition of function jf() if you are in the same execution context. Otherwise, replace function jf(){ ... with window.jf = function(){...
Also, running your tests in an inspector console might help.
First, use variables:
var jf = function () {
alert('1');
};
jf();
Then the second bit should work fine:
var func = function () {
alert('2');
};
jf = func;
jf();
Hi I am relatively new to javascript and jQuery and while trying to create a function the runs in intervals of 100 milliseconds I encountered a problem.I seem to get in the console of firebug and error witch says that clasing() is not defined.This is my code:
$(document).ready(function() {
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
$("img").not(":first").css("display","none");
function clasing() {
curent.removeClass("selected");
next.addClass("selected");
}
setInterval("clasing()",100);
});
What am I doing wrong here?Thank you
You have a scope problem. Your variables (prev, curent and next) are accessible inside .ready scope, such as your function clasing. But when you add this function to be called in a interval, using setInterval, this function should be in a Global scope (inside window object). Then, you should declare this function like window.clasing = function(){ ... }, but, doing this, the variables declared in .ready() scope will not be accessible running the function outside this scope, so all your variables must be in a global scope too. This should solve your problem.
However, this isn't a good programming practice, you should declare your variables inside clasing function, then they will be accessible only in function scope; And your function must be delcared outside .ready() function, and then you declare the interval inside .ready() function.
So, your code should be liek this:
function clasing(){
var prev = $("img.selected").prev();
var curent = $("img.selected");
var next = $("img.selected").next().length ? $("img.selected").next() : $("img:first");
curent.removeClass("selected");
next.addClass("selected");
}
$(document).ready(function() {
$("img").not(":first").css("display","none");
setInterval("clasing()",100); //or just setInterval(clasing,100);
});
Change setInterval("clasing()",100); to setInterval(clasing,100);
Change
setInterval("clasing()",100);
To
setInterval(function() {
clasing();
}, 100);
Right now your call to setInterval is running in global scope, but your function is defined inside your jquery function. Creating a closure will give you access to the jquery functions members.