Search code examples
javascripthtmlinputnumbers

How can i get a input number value in javascript?


I want to get the value of a input with the type of number. Here is the HTML

<input type="number" id="number" value="1">

and here is the javasript

const number = document.getElementById('number').value;

when i try to console.log(number) the result is 1 but when i increace the value of the input the result is still 1.

When i want to console.log(number) i want the result to be 1 but when i increase the value of the input like 3 i want the result to be 3.


Solution

  • I believe you want to update the number when it changes. Consider adding an event listener to the input element. Such that it updates the number variable every time you change it's value.

    const numberInput = document.getElementById("number");
    let number = numberInput.value;
    
    numberInput.addEventListener("change", (event) => {
      number = event.target.value
      console.log(number)
    })
    <input type="number" id="number" value="1" />