The input value I enter does not show up in JavaScript

Viewed 45

I am writing a text based game for a college competition and am very new to JS & HTML DOM. I have successfully created an input, and am trying to test it. However, when I type into the input and press enter nothing is logged onto the console...

function new_input(){
    let input = document.createElement("INPUT");
    input.setAttribute("type", "text");
    input.setAttribute("id", "input");
    document.body.appendChild(input);
    let x = $("input").val();
    console.log(x);
1 Answers

You do need to handle the click with the help of a callback.

When wanting to do so use the following code instead of the last two lines

input.onkeypress = (e) => {
    if(e.keyCode === 13) {
        console.log(input.value);
    }
}
Related