Noah
Noah

Reputation: 63

getElementById() not returning correct string

I am trying to grab the text from the textarea and it returns something but it returns nothing, no string.. When I enter a string into the textarea and click the button, it still returns nothing.

var name;
name = document.getElementById('username').value;

function action() {
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}

HTML:

<textarea rows="4" cols="50" id="username" placeholder="Enter your username here!"></textarea> <br />
        <button id="submit" onClick="action()">Submit</button>
        <br />
        <img id="theIMG"></img>

Upvotes: 1

Views: 64

Answers (3)

isopach
isopach

Reputation: 1938

You need to define name in the function itself, like this:

var name;


function action() {
name = document.getElementById('username').value;
document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
console.log("Working");
}

Upvotes: 1

tymeJV
tymeJV

Reputation: 104785

You should call getElementById inside the action method - that value won't persist as the textbox changes:

function action() {
    var name = document.getElementById('username').value;
    document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
    console.log("Working"); 
}

Upvotes: 1

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

At the time of execution of your code, value is "" only. And it will not change irrespective you change the value in html as you are not updating it in your script. Hence, you need to update your code to following

function action() {
    var name = document.getElementById('username').value;
    document.getElementById("theIMG").src = "https://crafatar.com/avatars/" + name;
    console.log("Working");
}

Upvotes: 1

Related Questions