user12597446
user12597446

Reputation:

JavaScript querySelector not working when .value is added to it

I am creating my program which takes the user input on an Enter key.

I use the userInput with .value in the if statement and it works perfectly. But when I try to use it as a variable, nothing is outputted and nothing is in the console.

I tried to do querySelector("input['name = "command"]') to see if it might work but again, nothing outputted and it showed nothing in the console

var userInput  = document.querySelector("input[name = 'command']")
var theInput = userInput.value.toLowerCase();
var theConsole = document.querySelector("#console");
theConsole.scrollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");

    function doAThing(event) {
        var theKeyCode = event.keyCode;
        
        if(theKeyCode === 13) {
        acceptCommand();
        setInterval(scrollUpdate, 1000)
        }
    }
function scrollUpdate() {
    myScroll.scrollTop = myScroll.scrollHeight;
}

function acceptCommand() {
    var p = document.createElement("p");

    if(theInput=== "help") theConsole.append("Help is given!", p);

    //using the keywords
    }
    

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body id = "scroll">
        <div id="game">
            <div id="console">
            </div>

            </div>
                <div id = "command-box">
                    <div id = "cmd">
                        <input type = "text" name = "command" id = "command" onkeypress = "doAThing(event);">
                    </div>
            </div>
        </div>    
    </body>
    </html>

Upvotes: 0

Views: 1158

Answers (2)

imvain2
imvain2

Reputation: 15857

You will want to refer to userInput.value instead of theInput. Because theInput is set to the value at the time of setting the variable and it doesn't get updated even though the value of userInput changing.

Upvotes: 0

smunteanu
smunteanu

Reputation: 542

Replace the div#console element:

<div id="console">

to this input:

<input type="text" id="console">

Upvotes: 1

Related Questions