somdow
somdow

Reputation: 6318

Function scope & variables in/out of said function

So im studying and just trying something out and well, the question is this

i know that a variable defined outside of a function is avail to all while one set inside a function is not.

that said when i do this

HTML:

<input type="text" name="field" id="field"/>

<input type="submit" id="submit" name="submit"/>

JS:

var results = document.getElementById("field").value;
var submitBtn = document.getElementById("submit");

function pushit(){
    aNames.push(results);
    for(i=0; i<aNames.length; i++){
        document.write(aNames[i] + "<br/>");
    }

    submitBtn.onclick = pushit;
}

it doesn't work. when submit is hit, it just displays the original array items.

but when i change the function to this:

function pushit(){
    var results = document.getElementById("field").value;
    aNames.push(results);
    for(i=0; i<aNames.length; i++){
         document.write(aNames[i] + "<br/>");
    }
}

essentially just putting the var results inside the function it works. my ? is why?

if i was to say for example, check in a form for a specific value of a field in the form, id check in the same manner, for the "value" of it against what i wanted to check so...im just not understanding why it doesnt work.

any tips, links, explanations etc...i gladly appreciate.

Upvotes: 1

Views: 53

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

The results variable in the first example, is set when the page loads, and is never changed. Each time you read it, it's the same value.

In the second example, you are getting the value from the input each time the event is ran; you are making a new variable. Thus, you are seeing the new values.

JavaScript DOM elements are "live" variables, but strings aren't.

For example:

var results = document.getElementById("field");
var submitBtn = document.getElementById("submit");

function pushit(){
    alert(results.results);
}

This works as results is a "live" variable. When you access it, it's always the latest DOM element.

When you do var results = document.getElementById("field").value;, now results is just a string; it's not "live" anymore.

Upvotes: 3

Related Questions