I'm trying to access a global variable in testGlob1, however I'm not able to do so:
var displayVar;
function globVariable(){
displayVar="2";
}
function testGlob1(){
alert(displayVar);
}
You aren't showing how your variable is being assigned a value. Is globVariable() being called on load of the document? Im sure this would work:
var displayVar=2;
function testGlob1(){
alert(displayVar);
}
Related
I am using Javascript and JQuery.
I have the following Variable var RoleID=""; and I have placed it outside of all functions.
I have a function
role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
var RoleID=data;
alert(RoleID);
})
}
This function gets the value of an <input type="text" id="emp_role"> and submits to a url='submitrole.php' using JQuery $.post and gets back an ID from url='submitrole.php' in return which is saved in RoleID and afterwards RoleID is alerted. This all is executed using <button onclick="role_submit();" type="submit">Submit</button> and works fine meaning that the ID which should come from url='submitrole.php' comes accurately and is also alerted accurately.
The issue arises when I use following function to look at the global variable var RoleID
function alert_roleID(){alert(RoleID);}
I call to this function using
<button onclick="alert_roleID();" type="submit" >Role ID</button>
This time the alert pops up showing nothing rather than the ID I got back from url='submitrole.php'. How can I get the global variable RoleID to have the value of from url='submitrole.php'?
There are two ways.
Set the variable to the window explicitly. Window is the global scope.
function role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
window.RoleID=data;
alert(RoleID);
})
}
Or define the variable in the global scope. If you do it this way, make sure you don't use var when you redefine it. If you use var it makes a new variable only visible in that scope (function).
var RoleID;
function role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
RoleID=data;
alert(RoleID);
})
}
Once you declared the variable outside, you should not use 'var' once again inside the function since this will recreate the local scoped variable instead of a global scoped variable and inaccessible outside the function. So you can remove the 'var' as below,
var RoleID = '';
role_submit(){
var role=$('#emp_role').val();
var url="submitrole.php";
$.post(url, {role2: role} ,function(data){
RoleID=data;
alert(RoleID);
})
}
My question is how to share a variable between two different javascript files. I am creating a form that transfers the value to a different page, which alerts that variable. I have 2 html files (index.html and form.html) as well as 2 javascript files (form.js and index.js). So basicly I want to share the variable theNick from form.js to index.js to display it using alert(). If this is not possible, is there another way to do this?
form.html:
<input type="text" id="Nick" placeholder="Nickname">
<a id="btn" onclick="submit()" href="index.html.">Submit</a>
form.js:
function submit(){
var theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
index.html:
<button onclick="callNick()">Click Me to view your Nickname.</button>
index.js:
function callNick(){
???????
alert(theNick); //I want to get access to this variable from form.js
}
By using the var keyword you are doing exactly the opposite. If you want to share something the easiest thing would be to bind the variable to the window object like this: window.theNick = ... and use it like alert(window.theNick).
It is sort of possible.
First of all you need to make certain that your HTML loads both JavaScript files. There isn't really a way for them to import each other, so the HTML must load both scripts.
Secondly, you need to modify your function submit to use a global variable. Global variables are initially defined outside the scope of a function. The function callNick is already looking for a global variable.
However, the submit function is defining its own, local variable because of the keyword var being used inside the function scope. Change it like so:
// Set global variable
var theNick;
function submit(){
// Use global variable
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
???
}
See this article for further information.
http://www.w3schools.com/js/js_scope.asp
You could just declare the variable outside of the function
var theNick; // you could omit this entirely since it will be declared in
// global scope implicitly when you try to assign it in the function
function submit(){
theNick = document.getElementById("Nick").value; //retrieves theNick from your input
}
javascript does not care about which files declarations are made but in which scope.
By placing the variable in global scope you'll be able to access it everywhere.
Global variables are not the best coding strategy but this should help you with the concept
It seems like you need to store the variable in the local storage object of the window object, this way you can set its value on the first page and retrieve it on the second.
page 1
window.localStorage.setItem("yourVariable", "yourValue");
page 2
var myVar = localStorage.getItem("yourVariable");
Only one 'caveat': this is a html5 feature, so it comes with limitations, check this link for more info.
You can pass your variable into the url, using the ?yourVar= GET mark :
form.js
function submit(e){
var theNick = document.getElementById("Nick").value; //retrieves theNick
e.target.href+='?n='+theNick; // set the href of your anchor with your variable
}
form.html
<input type="text" id="Nick" placeholder="Nickname">
<!-- We pass the event object into our function as a parameter -->
<a id="btn" onclick="submit(event)" href="index.html">Submit</a>
index.js
function callNick(){
// get the variable from the current location
var theNick = window.location.href.split('?n=')[1];
alert(theNick);
}
index.html
<button onclick="callNick()">Click Me to view your Nickname.</button>
▶︎ Plunker where "form" has been changed to "index" and "index" to "result".
Note :
To pass multiple variables, you can use the & delimiter, and then use the window.location.search property as done in this CSS-tricks article.
▶︎ Multiple vars plunker
My code is...
<script type="text/javascript">
function changeval() {
$total = parseInt($("#small").val()) + parseInt($("#medium").val());
}
</script>
How can I pass '$total' to another js file, say main.js.
Call changeval function from another file, save/use returned value.
function changeval() {
return parseInt($("#small").val()) + parseInt($("#medium").val());
}
Or have one global variable save value inside the same variable and access it from another file.
Make sure that $total is assigned to the global scope and make sure the script where you want to use it is below the script where you assign it. Be careful about polluting the global scope too much because it can make code that is very tricky to debug and can cause strange errors if you overwrite a native global variable.
How do I change a variable in a jQuery function?
Do I have to override the entire function?
Below is a function found in jquery.dataTable.js
How do I add a "," to the sValidChars variable.
$.extend(DataTable.ext.aTypes, [
function (sData) {
....
var sValidChars = "0123456789.";
....
}
]
You will have to override the entire function/change the code in the actual file.
It is because sValidChars is a local variable to the anonymous function, so it cannot be accessed outside the function scope.
My application is accessing a third party external JavaScript file that I cannot alter.
Within the file is an object defined similarly to as follows:
object_1 = (function(){
var object_1_var = 'object_1_var_value';
return {
obj_1_func: function() {
console.log(object_1_var);
}
}
})(window);
I need to be able access the object_1_var within the object, but I'm struggling to access it.
object_1.v // returns undefined
object_1.obj_1_func() // returns the value via console, but I need to assign it to a var.
I have tried extending the object using as follows: (Using jQuerys $.extend())
object_2 = (function(){
return {
obj_2_func: function() {
return object_1_var;
}
}
})(window);
$.extend(object_1, object_2);
var my_var = object_1.obj_2_func(); // returns 'Uncaught ReferenceError: object_1_var is not defined'
What can I do to be able to access object_1_var?
You will not be able to access the variable. It happens to be a private member. Private members of an object can be accessed only by its member functions.
Read this.
object_1_var is a lexically scoped local variable.
That means that it can't be accessed by extending object_1 outside of its original definition.
The only way it can be accessed is by adding functions within the original lexical scope in which it was declared:
object_1 = (function(){
var object_1_var = 'object_1_var_value';
return {
obj_1_func: function() {
console.log(object_1_var);
}
var_1: function(x) {
if (typeof x !== 'undefined') {
object_1_var = x;
} else {
return object_1_var;
}
}
}
})(window);
but since you can't modify object_1, you're out of luck, I'm afraid!
Make it public, like this:
object_1 = (function(){
var object_1_var = 'object_1_var_value';
return {
obj_1_func: function() {
console.log(object_1_var);
},
object_1_var: object_1_var
}
})(window);
EDIT
If unable to edit the javascript (such as in a third party library - sorry for omission) then you will not be able to have access to object_1_var as it's scope is local to the closure object_1.
What you are trying to accomplish is impossible in JS.
With the construction of object_1 the variable goes out of scope of that method. The reason why the logging function can access the variable is what we call 'a closure'.
Sadly, object_1_var isn't accessible in this example. The variable is defined as local to within that particular function - the only reason that the other functions can see it is because they are also defined within that function. This "closure scoping" is an interesting feature in JavaScript that you don't see very often elsewhere, but is the only real way of defining "private" variables in JavaScript Objects.
Hope that helps!
In a worst case scenario, in the past I've worked around this sort of issue by effectively overwriting the definition of an object that was previously defined elsewhere - mainly in Greasemonkey scripts - but I wouldn't condone this for production uses!
The trick here is to just copy the entire piece of script into your own. It's ugly as hell, but it might just work! (YMMV)