I can't figure out how to append a user's input into an array in Javascript

MHamza911119 :

I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:

<html lang="en">
  <head>
    <title>Magic 8 Ball!</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="css/style.css">
  </head>  
  <body>
    <div class="container">
        <h1>Magic 8 ball</h1>
        <h2>Ask your question, then click on the button!</h2>
        <div class="eightBall">
            <div id="output">
                <p id="result">8</p>
            </div>
        </div>
        <div class="inpBox">
            <input type="text" id="inputBox"></input>
            </div>
        <div class="buttons">
            <button id = "addButton" type="button">Add</button>
            <button type="button">Custom</button>
            <button id = "defaultButton" type="button">Default</button>
            <button id = "Ask" type="button">Ask</button>
        </div>
    </div>
  </body>
  <script src="js/main.js"></script>
</html>

And the Javascript:

console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
    customList.push(inputText);
    console.log(customList);
});

Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it. An image of the console log: https://imgur.com/a/AiV4hRM I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.

Sohail :

You need to get the value of the input from value attribute.

The below code will just return the reference to the input not the value.

var inputText = document.getElementById("inputBox");

To get the value of the input, you need to get it from the value attribute.

var inputText = document.getElementById("inputBox");
console.log(inputText.value);

Working Example:

let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
    let inputValue = inputText.value;
    if (inputValue) {
        customList.push(inputValue);
        console.log(customList);
    }

});
    <input type="text" id="inputBox">
    <button type="button" id="addButton">Click me</button>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301973&siteId=1