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
Here is some code: window. onload = function show(){ var x = 3; } function trig(){ alert(x); } trig();
To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.
JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With