javascript: get a function's variable's value within another function

Maria picture Maria · Aug 5, 2012 · Viewed 115.8k times · Source

okay so I have this code in body:

<input type="text" value="haha" id="full_name"/>

And this code in script

<script language="javascript" type="text/javascript">
    function first(){
        var nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

I want a alert showing the value of the element full_name, but it doesn't seem to work, does anyone know why? :S

Answer

Blender picture Blender · Aug 5, 2012

nameContent only exists within the first() function, as you defined it within the first() function.

To make its scope broader, define it outside of the functions:

var nameContent;

function first(){
    nameContent=document.getElementById('full_name').value;
}

function second() {
    first();
    y=nameContent; alert(y);
}
second();

A slightly better approach would be to return the value, as global variables get messy very quickly:

function getFullName() {
  return document.getElementById('full_name').value;
}

function doStuff() {
  var name = getFullName();

  alert(name);
}

doStuff();