简体   繁体   中英

Javascript Input Value Is Undefined

I've been trying to reference an input from my HTML through Javascript, and for some reason no matter what I enter in this text field it always returns undefined... why is this so?

Javascript:

const button = document.getElementById("button");
const code = document.getElementById("textArea").value;


if (button === null) {
    alert("Button is null");
} else if (code === null) {
    alert("Code is null");
}

button.addEventListener("click", function(){
    console.log("Submitted!");
    console.log(code);
});

button.addEventListener("click", function(){
    console.log("Submitted!");
    getInputValue();
});

HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Code Sorter</title>
</head>
<body>
    <textarea id = "textArea" rows = "10" cols = "50" placeholder="Type something..."></textarea>
    <button id="button" value = "submit">Submit</button>
    <script src = main.js></script>
</body>

</html>```

Very simple. First: How often do you set the variable code? Once, at the start, when it will always be undefined. Just because textfield.value changes does not mean that code is reevaluated.

The solution is to get the text from within your button handler.

button.addEventListener("click", function(){ 
    console.log("Submitted!");
    console.log(document.getElementById("textArea").value)});

If you remove the.value from the.getElementById and put it on the button.addEventListener, it works:

const button = document.getElementById("button");
const code = document.getElementById("textArea");

if (button === null) {
    alert("Button is null");
} else if (code === null) {
    alert("Code is null");
}

button.addEventListener("click", function(){
    console.log("Submitted!");
    console.log(code.value);
});

button.addEventListener("click", function(){
    console.log("Submitted!");
    getInputValue();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM