I would like some help please.
I managed to make my code work after finding a similar question on Stack Overflow, but the method I've been trying previously doesn't seem to work at all.
My code is very simple, if the number is 2 and I click the button, the message will say "Correct". If the number is anything else, it will say "Wrong".
Below is the HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<input type="number">
<p>Message</p>
<button>Update</button>
</body>
</html>
Here is the JavaScript code that works Codepen link
const message = document.querySelector("p")
const button = document.querySelector("button")
function myFunction() {
const number = document.querySelector("input").value;
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
Here is the code that doesn't work Codepen link
const message = document.querySelector("p")
const button = document.querySelector("button")
const number = document.querySelector("input").value
function myFunction() {
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
My question is, why doesn't my second JavaScript code work? Is it possible to keep the number const outside of the function (keep the const variable global)?
As the tutorials I'm watching suggest you keep variables outside functions to prevent DRY.
Also, how can I get the code to run without having to click the "update" button each time ?
e.g. if I type 2, the message will automatically say "Correct".
Thank you very much in advance.
CodePudding user response:
const number needs to be in the function, otherwise the const will be null always
function myFunction() {
const number = document.querySelector("input").value
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
Live update on keyup inputfield
const inputfield = document.querySelector("input");
inputfield.addEventListener("keyup", myFunction);