Is something wrong with the editor?

I’m getting an input value from an input box.
const number = document.getElementById(“number”).value; when I use this variable in my if statements it does’t work. When I creat a const variable = number.value and use that, it doesn’t work. When I use number.value directly in the if statements everything works. Am I missing something? Or there’s a problem with the editor? Thanks.

which editor are you referring to?
If you are trying to get help with a specific fCC challenge, please click the Help button to open a post with all relevant details included.

It sounds like you are saving the value at the top of the file, or at least outside any function that would re-run (i.e. an event handler).

When you use the DOM element value directly in your if statement it gets re-evaluated every time the statement runs. Code at the top of the file or outside functions that re-run, only get executed one time, so you end up with a single value that never changes.

Getting user input has to be event driven, so using change, input or click events, and then inside the handler function you get the input value, either from the event target event.target.value or from the element someElement.value.


<input type="text" id="name">
const inputElement = document.querySelector("input");
// doesn't work, the value is an empty string and it is never re-evaluated
const inputElementValue = document.querySelector("input").value;

inputElement.addEventListener("input", (e) => {
  console.log(inputElementValue); // always an empty string ""
  console.log(inputElement.value); // whatever value was typed
  console.log(e.target.value); // whatever value was typed
});

Thank you for a detailed explanation. Now it makes more sense.