'input.innerHTML returns an empty string

I write html code this

<input type="text" class="inputstyle" id="text" name="text">

so this is JS code

function addtolist() {
//get input
var textappend = document.getElementById("text").innerHTML;
console.log(textappend);
console.log(typeof (textappend));
console.log(choice)
if (textappend != "") {
    choice.push(textappend); // append text to choice
}
    document.getElementById("list").innerHTML = choice; // output list 
}

And i make button if click button. Button will call addtolist() function and this function will append id="text"(type string) to the choice(brank array). I try input text "Hello World" to <input> but addtolist() function it's append blank string to choice. idk why help me solve it pls. (sorry for my grammar I don't english pro)



Solution 1:[1]

To get the value of a <input type="text" element, use .value rather than .innerHTML.

var textappend = document.getElementById("text").value;

Solution 2:[2]

So assuming that you have a h1 inside HTML that contains the text that you want to use, you can just use .value instead of .innerhtml, I would suggest you to use it as your project gets bigger using .innerhtml may get complex so use .value instead.

This should be your JS code:

function addtolist() {
//get input
var textappend = document.getElementById("text").value;
console.log(textappend);
console.log(typeof (textappend));
console.log(choice)
if (textappend != "") {
    choice.push(textappend); // append text to choice
}
    document.getElementById("list").innerHTML = choice; // output list 
}

Hope it helps out!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 One.Punch.Leon
Solution 2