NavinRaj Pandey
NavinRaj Pandey

Reputation: 1704

How to access the variable from one function to another function in Javascript?

I have prompt dialog box which take Email value and need to pass the Email variable in another function Email(). Here is my code.

function promptMessage() {
    public var Email = prompt("Enter your Email :", "");
}
function Email(){
    alert("Email Address is " +Email); //Email from promptMessage() function 
}

Upvotes: 0

Views: 3736

Answers (3)

Nishu Tayal
Nishu Tayal

Reputation: 20880

Since you are declaring the Email variable inside a function(in local scope), that's why it is not accessible outside of this function. Instead, define it outside like this as a global var :

var email;
function promptMessage() {
    email = prompt("Enter your Email :", "");
}
function Email(){
    alert("Email Address is " +email); //Email from promptMessage() function 
}

Upvotes: 0

Musa
Musa

Reputation: 97717

How about

function promptMessage() {
    return prompt("Enter your Email :", "");
}
function Email(email){
    alert("Email Address is " +email); //Email from promptMessage() function 
}
Email(promptMessage());

Upvotes: 3

Iznogood
Iznogood

Reputation: 12853

Just declare it outside of the scope of the functions and dont use a function name as a variable name this will leed to nightmares:

var EmailAddr;

function promptMessage() {
     EmailAddr = prompt("Enter your Email :", "");
}
function Email(){
    alert("Email Address is " +EmailAddr); //Email from promptMessage() function 
}

Upvotes: 1

Related Questions