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
This question is related to
javascript
function
variables
call
you need a return statement in your first function.
function first(){
var nameContent = document.getElementById('full_name').value;
return nameContent;
}
and then in your second function can be:
function second(){
alert(first());
}
Your nameContent scope is only inside first function. You'll never get it's value that way.
var nameContent; // now it's global!
function first(){
nameContent = document.getElementById('full_name').value;
}
function second() {
first();
y=nameContent;
alert(y);
}
second();
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
Your nameContent
variable is inside the function scope and not visible outside that function so if you want to use the nameContent
outside of the function then declare it global
inside the <script>
tag and use inside functions without the var
keyword as follows
<script language="javascript" type="text/javascript">
var nameContent; // In the global scope
function first(){
nameContent=document.getElementById('full_name').value;
}
function second() {
first();
y=nameContent;
alert(y);
}
second();
</script>
Source: Stackoverflow.com