hawks
hawks

Reputation: 49

How do I access the output of JavaScript function outside the function?

Been stuck on this for a while now and it is really annoying me. I have a form in HTML that lets the user enter some text, I then created a function in my script to take that text when the user presses submit. The function works fine as it takes the input and stores it in input (i console logged it and it was right). My issue is that i want to take that input and use it outside the function to produce graphs in d3 by filtering using that text that the user input.

I have tried using the code below but it doesn't work, when logging user it says its undefined and hence i cant use it further could some please help.

    var user;
    function othername(){
        var input = document.getElementById("user_name").value;
        console.log(input);
        user = input;
    }
    console.log(user)
</script> 

Upvotes: 0

Views: 557

Answers (2)

The code you provided does:

  1. Declares user variable.
  2. Declares function which uses the variable, but the function is not yet executed.
  3. Immediatelly prints the variable user, which is still undefined because the function wasn't called yet.

If you want to log user variable later, you need to wrap it in the function for example. Then, when you call the wrapper function, it logs the value as you expect.

var user;
function othername(){
    var input = document.getElementById("user_name").value;
    console.log(input);
    user = input;
}
function logUserValue(){
    console.log(user);
}

Upvotes: 0

Quentin
Quentin

Reputation: 943579

You have to call the function before it has any effect:

var user;
function othername(){
    var input = document.getElementById("user_name").value;
    console.log(input);
    user = input;
}
othername();
console.log(user)

However, globals are dangerous. Use return values instead.

var user;
function othername(){
    var input = document.getElementById("user_name").value;
    console.log(input);
    return input;
}
user = othername();
console.log(user)

However, since you are reading from an input, you probably don't want to call it until some event happens (such as a button being clicked) so the user has a chance to type something into the input first.

In which case you have just reached the territory of How do I return the response from an asynchronous call?

Upvotes: 1

Related Questions