As total JavaScript beginner I am unable to use global variable while trying to use multiple functions. The code is as follows –
<script type="text/javascript">
/* Global Variable example! Not working as one function called onClick. */
function make_name_variable () { var y_name = document.getElementById('y_name').value; }
function make_date_variable () { var y_date = document.getElementById('y_date').value; }
function make_month_variable () { var y_month = document.getElementById('y_month').value; }
function make_year_variable () { var y_year = document.getElementById('y_year').value; }
function test(){
/*var y_name = document.getElementById('y_name').value;
var y_date = document.getElementById('y_date').value;
var y_month = document.getElementById('y_month').value;
var y_year = document.getElementById('y_year').value;*/
document.getElementById('Result').innerHTML = y_date + y_month + y_year;
return true;
}
function compute () {
make_name_variable ();
make_date_variable ();
make_month_variable ();
make_year_variable ();
test();
}
</script>
Using as:-
<input type="submit" value="Submit" onclick="compute ()">
Unable to get the result as expected. I want to use the data through out the page so wanted to keep it global for all functions to use. I was not able to set it global in the conventional way as well. Declaring the variable within function gives desired result.
As you must have a realized I am a complete noob so if there are other ways to get the things done please enlighten me. Somehow I feel there must be a better and easier way to solve this.
Thanks in advance. 🙂
P.S: First question here. Excuse my mistakes.
The
varkeyword declares a variable in the current scope. If you declare avarinside a function, it will only exist there. The MDN docs are generally very nice.