Variable Scope Inside A Function

Oct 30, 2006

I think I've had JavaScript variable scope figured out, can you please
see if I've got it correctly?

* Variables can be local or global
* When a variable is declared outside any function, it is global
regardless of whether it's declared with or without "var"
* When it is declared inside a function, if declared with "var", it's
local, if not, it's global
* A local variable that is declared inside a function is local to the
whole function, regardless of where it is declared, e.g.:

function blah() {
for(var i ... ) {
var j ...
}}

i and j will both be visible within blah() after their declaration.
* the notion of "function" in this context also applies for this kind
of construct:

var myHandler =
{
onClickDo: function()
{

in the sense that whatever one declares inside onClickDo with "var"
will only be visible inside onClickDo. What else, am I missing anything?

View 4 Replies


ADVERTISEMENT

Scope Inside A Prototyped Function?

Sep 8, 2006

I'm trying to access some of the global's inside my class LiveSearch
and I have no idea how to go about it. Here is what I have so far:

<script type="text/javascript" src="query.js"></script>
<script type="text/javascript">
function LiveSearch(global) {
this.theglobal = global;
this.initialize();
}

LiveSearch.prototype.initialize = function() {
$("#thebutton").mousedown(function() { //when we click the button
alert(this.theglobal);
});
}

$(document).ready(function() {
var objSearch = new LiveSearch("globalvalue");
});
</script>

On page load I create a new LiveSearch instance and it assigns
theGlobal = "globalvalue" and proceeds to initialize(); At this point
Im using JQuery to setup an onmousedown event on a button on my page
with id="thebutton". When I click the button the alert comes back with
'undefined'. How can I get direct access to my theglobal variable? Code:

View 1 Replies View Related

Resolved Undefined Variable In Function - Scope?

Oct 27, 2009

I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me.

I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself.

I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time.

[Code]...

View 2 Replies View Related

Declare A Variable Inside A Function - Returns White Space - Not Variable Value

Aug 17, 2010

I am trying to declare a variable inside a function and use it later on in my code... but it just already returns white space... i.e. not variable value. I am setting it within this function:

function show_video1(){
document.getElementById('video1').style.display="block";
var video1Name = "Education World News (Part 1)";
document.getElementById('video2').style.display="none";
document.getElementById('video3').style.display="none";
document.getElementById('video4').style.display="none";
[Code]...

and trying to call it later on with this: <script type="text/javascript">document.write(video1Name)</script> It might be worth noting that each one of my 11 videos will hace a different name.

View 13 Replies View Related

Using Variable In Php Inside The Function?

Feb 15, 2011

In my code a JavaScript function received value from html hyperlink. Value passing successfully, inside product function document.write(a) printing value 5. But how can i print value of "a" inside product function by php. My code is here....

<html>
<body>
<a href='javascript: product(5);'>click</a>
<script type='text/javascript'>

[code].....

View 7 Replies View Related

Passing Variable To A Function Inside A Function?

Feb 10, 2010

Here is the code:

for (var i = 0; i < BS_crm['activityTypes'].length; i++) {
var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); };
var type = {

[Code]....

Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to:

var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); };

View 4 Replies View Related

Implementing A Variable's Value Inside A Function

Jan 9, 2008

I'm making a project which creates tabs with a class. I don't really know how to explain it better but this is how it works:

<a href="#" id="tbs_tabs">Create</a>
<script type="text/javascript">
var tbs = new Tabs('tbs_tabs');
tbs.theme = 'classic'
tbs.create_option('abc','#');
tbs.create_option('abz','#');
tbs.create_option('abf','#');
tbs.create();
</script>

It first creates the new class and tells it the id, then it creates as many options as you want and creates it.

My problem is with this line:
for(i=0;i<this.option_values.length;i++)
{
li = document.createElement("LI");
li.appendChild(document.createTextNode(this.option_values[i]));
addEvent(li,"click",function(){oThis.select_option(i); return false;};

ul.appendChild(li);
}

What I was trying to do here is add an event to the LI element that refers to the current tab class but doesn't use the CURRENT i value but the value that was when the event was first created.

For example.. If my i value is currently 2 and I add the function, then I want that when I call the function, the value will still be 2 and not the current i value. What happens now is when I call the function the value is something like 5 or 6.

View 2 Replies View Related

Variable Inside A Dynamically Created Function?

Jan 20, 2010

I have a set or icons that which over time I replace with a different icon and and add a onclick event to them. This is my code

function updateStatusIcons(retText) {
updatingStatuses = true;
var updates = retText.split("|");
for (z=0; z<updates.length; z++) {

[Code]....

Everything works fine except for the onclick event. In the hover message of the icon, the correct project ID is displayed in the message, hoever in the function, the onclick funtion always loads the page with the last set project id. How can I pass the project id into the onclick function and make it stay fixed and not be the value of that it was last set to?

View 2 Replies View Related

Changing Global Variable Inside Function

Nov 26, 2010

im trying to change a variable set outside of a function and calling the function with an onchange... i'm having problems getting the variable to change

<script type="text/javascript">
var price = '<?php echo $price; ?>';
function addtwo()
{
if(document.add.size.value == "2xl")
{
price = price + 2;
}
}
</script>

View 4 Replies View Related

Make A Variable Inside A Function Global?

Mar 6, 2010

Is it possible to make a variable inside a function global (or at least usable in other functions)?

View 2 Replies View Related

Placing A JS Function Variable Inside A Form?

Dec 29, 2010

This is a follow-up to a post from long ago. I had thought that this would be very simple but damned if I can get it to work.

Basically, I want a value which is generated in a JS function to be included in a <form method="get"> output. For some reason which is beyond me, the value is not being updated and the form is returning only 'undefined'. Here is the code:

JS:
<script type="text/javascript">
function addRow(tableID) {
// CELL 1
var table = document.getElementById(tableID);

[Code]....

For the record, the page is up here: [URL]

View 8 Replies View Related

Setting Parent Class Variable From Inside Function?

Sep 8, 2009

Ok...so here is what I have:

function myClass() {
this.checkLogin = function(name,pwd) {
if(name.length > 0 && pwd.length > 0) {[code]....

Everything works above. The first alert shows that this.status was set to 'error'. However, if I call myClass.getStatus(), I get undefined. How can I get the parseData function to set the variables in the parent function?

View 1 Replies View Related

Jquery :: Php - Variable Not Changing Inside Click Function

Dec 22, 2010

I have a list of most 17 recent entries from a db table and wanna use jquery/ajax to have a next button that loads the next 17 entries when you click it. It passes the 17 variable to the .load which works fine first time around (this is later used as mysql limit), but then I try to increase the start variable with 17 so that next time I click it would pass 34 to the .load (so it loads next 17 again) but this doesn't work, it simply loads same 17 again on 2nd, 3rd ect. click (so nothing changes). use global variables by setting it with var and using it without var inside the function.

<script>
var start = 17;
var loadUrl = '<?php echo site_url('welcome/battles'); ?>';
$("#latestbattlesnext").click(function () {

[code].....

View 2 Replies View Related

Access/change Variable Inside Lambda Function?

Aug 17, 2010

In one of my functions I got the following lambda function. It works as intended, but I got a tiny problem. I'm trying to access the function-scooped variable "matched" and set it's value to "true". The problem is that it seems like the variable is existing as a local variable inside the lambda function, even if it's not declared inside the lambda function itself. So, the change "matched = true;" does not effect the variable that I declared.

Code:

//... code
var matched = new Boolean(false);
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {

[Code].....

View 3 Replies View Related

Variable Scope

Jul 20, 2005

If I do . . .

myForm=document.tstForm;
function initialSetup(){
myForm.fld01.value="Test 01"
myForm.fld02.value="Test 02";
myForm.fld01.focus();
}

Then, in the body tag, I do onLoad="initialSetup()",
the script doesn't work and I get a "myForm has no properties" error

I know it'll work if I move it within the function, but I figured a
global variable would retain its value within the function. Why not?

View 2 Replies View Related

JQuery :: Cannot Get Variable Inside Loop Back To Original Function

Oct 22, 2009

I'm having some problem with return value for a function. I'm trying to access google blogger's API to display blog entries on my site. I'm doing this through JQuery and requesting a JSON response. Everything seems to work ok, but I want to access the link for the blog entry. This is a subset of the "entry" object.

It's structured like this:
Entry:
title,
content,
link:
rel,
type,
href,
rel,
type,
href,

I want to get the link where the "link.rel == "self". To do this I have to loop through the link object (5 times). The loop and conditional statement works correctly, but I can't get the variable inside this loop back to my original function.

I have this code:
$.each(data.feed.entry, function(i, entry){
$.each(entry.link, function(j, link){
if(link.rel == "self"){
var postlink = link.href;
alert("link : " + postlink);
return postlink;
}});
alert(postlink);
});

View 2 Replies View Related

JQuery :: Access Variable Inside Callback Function Of Post?

May 4, 2010

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var global_var = false;
function test_func() {
$.post("server.php", function(data){
alert("Data Loaded: " + data);

[Code]...

View 2 Replies View Related

Variable Scope And Closures

Jul 23, 2005

Given the following working code:

function attributes() {
var attr1 = arguments[0] || '_'
var attr2 = arguments[1] || '_'
return (
function (el1, el2) {
var value1 = el1[attr1] + el1[attr2];
var value2 = el2[attr1] + el2[attr2];
if (value1 > value2) return 1;
else if (value1 < value2) return -1;
else return 0;
}
);
}

var a = [
{ a:'smith', b:'john' },
{ a:'jones', b:'bob' },
{ a:'smith', b:'jane' }
];
a.sort(attributes('a', 'b'));
for (var i =0; i < a.length; i++) {
document.write(a[i].a + ', ' + a[i].b + '<br>');
}

My question is, are attr1 and attr2 guaranteed to exist through
the lifetime of a.sort(attributes('a', 'b'))?

As I understand it, the anonymous inner function reference I am
returning is a property of attributes(). As such, when I return a
reference to the anonymous inner function, the outer attributes()
function must continue to exist (as must attr1 and att2) until
there are no further references to the inner anonymous function.

As a result, there is no danger of attr1 or attr2 "disappearing"
during the repeated calling of the anonymous inner function.

Is my explanation basically correct, or am I deluding myself and
I'm just lucky that the garbage collector hasn't recovered attr1
or attr2 while the sort is still going on? In other words, is the
behaviour I'm seeing consistent and predictable, or should I
change my approach?

View 3 Replies View Related

Using The Switch Statement And Variable Scope?

Jun 14, 2010

I've created a jQuery script that uses a switch statement. However, my experience with it, relative to variable scope, doesn't seem to follow the logic.According to the JavaScript/jQuery theory, a global variable was accessible (meaning read & write) throughtout any function within any script (one that page).However, apparently that theory wasn't completely true as it pertained to switch statements that contained variables. To illustrate my case in point, I've included a simplistic version of my code:

$("#selector").delegate("div", "click", function(event) {
var testVar = 4;
switch (this.id) {

[code]...

As shown, the variable "testVar" is not accessible from one case to the next case .Furthermore, to add insult to injury, I am seeing the same behavior within the conditional if else statement counterpart to the switch statement.

View 1 Replies View Related

Variable Scope In Onclick Event

Oct 17, 2010

I have this web application where users are able to fill out and submit reports. The reports and scripts are part of a whole system, that is, they are used on a couple of different clients written in both vb and c#. This is the web-version of those clients.The scripting language is javascript and is executed using different script engines on the different systems. But for the web-version it is just executed in the browser.The different fields in the report can be accessed by typing:ID1.value. To get ID1 to apply for the input-field with id ID1 I had to in the initfunction of the page write a window["ID1"] = document.getElementById("ID1");

But my problem is when this element change. Cause in the report I have a special element that in the browser is translated to a table-element with a report-field in each cell.When I switch the current row, I need to update the window["ID1"] to equal the correct report field on the selected row. But when trying to access the new variable ID1 from a buttons onclick event it is undefined.<input type="text" id="test" onclick="alert(ID1.value);" />What I think happens is that when the page is first drawn the onclick event is created and as I understand, variables inside an event has the same value as when the event was created.

So if ID1.value was something when the page was created it will be the same when it is called even if the value of ID1 is different. And that seems to be the case. When I debug the page, before entering the event, ID1.value has the correct value while inside the event it is undefined and after the event it has the correct value. If I write window["ID1"] correct value is also shown.But a weird thing is that in another place in the code I had the same problem but instead of having the code inside the onclick event I first had a global function changeActiveRow and inside that I had an eval, eval(document.getElementById("ID1_script")) where ID1_script is a hidden element whos value is a script using ID1.value and that works.

View 3 Replies View Related

Objects, Callback Functions And Variable Scope

Nov 23, 2005

I am trying to convert some of my javascripts into a class and am
running into difficulties which i think are related to variable scope.

Basically I have a constructor function for a calendarInput class that
takes 4 parameters, the first is a reference name/number for this
input. I also have some functions for importing my PHP classes into
Javascript using AJAX (properties only. still trying to get methods
working but that's another story!). The relevant function is called
call_object_method(classname, methodname, createparams, methodparams,
post, callbackfunction). This creates an instance of the specified PHP
class using the parameters in createparams. It then calls the
specified method using the parameters in methodparams. The result is
passed back to the javascript function specified in the callbackfunction parameter (ie the value of xmlhttp.onreadystatechange is set to callbackfunction before xmlhttp.send() is called)

The function i am trying to fix is called show (x,y) which creates the
html for the calendarInput and displays it at co-ordinates x, y.

So, my code is as follows:

function calendarInput(calendarid, target, displaytarget, value)
{
this.calendarid = calendarid;
this.target = target;
this.displaytarget = displaytarget;
this.value = value;

this.show = function(x, y)
{
<!--// bunch of init and prepping code. includes creating
createparams and methodparams arrays //-->

call_object_method("cms_calendar", "getcalendarview",
createparams, methodparams, false, this.showcallback);

}

this.showcallback = function()
{
alert(this);
<!--//code to create html//-->
}

}

I know i've cut out most of the innards of this. This is because I
have already tested these functions and had the calendarInput working
outside of a class, hence am pretty sure that this is ok (plus it runs
to almost 1000 lines these days!!). My problem is that when I call the
show method, the alert on the first line of the callback function
returns the function showcallback instead of (as i was expecting) the
instance of the calendarInput object. Whilst this kinda makes sense I
can't figure out how to reference the Object instead. I have tried
'this.parent' but this returned undefined. I have tried changing the
way i reference the callback function (ie the final parameter of
call_object_method) but no joy.

View 2 Replies View Related

JQuery :: Variable Scope And Un-named Functions?

Aug 23, 2010

I've recently started developing javascript using jQuery and so far I'm really enjoying it.Being a professional programmer (mainly C, C++, java and python) there is one thing that's been puzzling me regarding variable scope and unnamed function declarations. Let me exemplify:

------------------------
var sum = 0;
$(xmlobj).find("item").each(function(){

[code]....

View 6 Replies View Related

Can Set Context / Scope For MyStartAction So It Can Access Variable?

Jan 31, 2011

[code]how i can set context/scope for myStartAction so it can access (this.url) variable?console.log(dd.url) will work but i can't predict what name will object have (that depends on user) there might be more than one instance of myObject

View 10 Replies View Related

Variable Scope - Anonymous Functions And Self Invoking Closures

Jul 25, 2011

I think the last thing people seem to learn about in JavaScript when they're not coming from other programming languages is variable scope. Some even get all the way into AJAX without having learned about scope, and this is a time when it's really needed. Although the scope of JavaScript variables is non-complex by nature, it's something we should all get a full understanding for before we move too far.
Section 1: What is "scope"?
Section 2: The "var" keyword
Section 3: The "this" keyword
Section 4: Closures or "Anonymous functions and self-invoking closures

View 5 Replies View Related

JQuery :: Call The Delete/refresh Function From Outside The Event's Function Scope?

Apr 4, 2010

I'm wanting a table cell click event to remove and replace the table it was clicked on, however I'm finding that as it's deleting the original table object the actual running event code is being replaced and the function is bailing.how I can call the delete/refresh function from outside the event's function scope?

View 1 Replies View Related

Send A Loop Variable (i) To A Function Inside The Loop

Aug 4, 2011

I'm looking to send a loop variable (i) to a function inside the loop, but I can't seem to get it to use the value I want, it keeps making it a reference of i and therefore the function is always called using the last value of i rather than the one it was set with.

So if i have 5 Tabs then Tab 1, when clicked, should call DefaultTabClick(0) and so on rather than always using 4 for any of the tabs.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved