• Register
499 points

How to get value from one function to another in javascript

We can do this two ways.Scope matters to make available the variable outside the function.Scope of the variable inside of the functions is inside the function.It is not available outside.

Option 1

You can define those variables outside of both functions like:

var radio;
var fname;
getdata() {
    radio = document.getElementsByName("radiobuttonlist1");
sendinfo() {

And then whenever the values of those variables is updated it will be updated at the scope those variables were initially defined (outside those functions).

The scope of a javascript variable is within the curly braces {} that variable is in and any curly braces within that set. Scope in javascript often refers to those curly braces {}. There are exceptions including the if statement in which you can define variables inside of and access outside (assuming the condition was true).
There is second option too get this done and work for us,

Option 2

Or you can pass those variables as parameters to the second function like: sendinfo(radio, fname);

Passing values by returning them

You can return the values as an object literal in your getdata() function like this:

getdata() {
    return {
        radio : document.getElementsByName("radiobuttonlist1"),
        fname : document.getElementById("Firstnametxt").value

Then do this:

sendinfo() {
    var data = getdata();

And then access those variables like: data.radio and data.fname.

1 Comment

The material you wrote is quite beneficial. Thank you.