Why is the value of my input always empty if I store it in a variable?

后端 未结 1 1787
温柔的废话
温柔的废话 2020-12-12 04:32

I’m trying to get the value property from my field so I can later use it to fetch data from a specific API URL.

The problem i

相关标签:
1条回答
  • 2020-12-12 05:14

    The testing function handler is called every time the button is clicked.

    In contrast, the inputValue variable is evaluated only once when the code is firstly executed, at initial script evaluation during page load, and never again. The input value gets stored inside the variable and it never gets updated after that. (Strings are immutable in JavaScript: once you store a string in a variable, it won’t change unless you assign that variable to another value.)

    If you want to refresh the value every time you click the button, you have to query the element every time:

    const testing = () => {
      const inputValue = document.getElementById("inputField").value;
    
      alert(inputValue);
    }
    

    Or you can keep just a reference to the element and query the value property every time:

    const inputElement = document.getElementById("inputField");
    const testing = () => alert(inputElement.value);
    
    0 讨论(0)
提交回复
热议问题