Home > Net >  Updating value of variable based on value of HTML input
Updating value of variable based on value of HTML input

Time:02-15

I have an HTML input that accepts only numbers and on my script file I have I variable that gets the value of the input. What I want to do is create another variable that is equal to the first variable. When I put a number on the input field the value of the numInput variable changes but not on the
value variable

const numInput = document.getElementById("input");
const value = numInput.value;
<header> 
   <input type="number" name="numInput" id="input"  min="0" value="1" required>
</header>

CodePudding user response:

The reason value does not change is because it is saving a copy of the numInput.value content during the assignment, not a pointer or reference (something that I don't think you could do on JS). I would suggest using just using .valueAsNumber as suggested by @Sebastian Simon.

CodePudding user response:

To accomplish this, JavaScript needs to trigger a function when the input value of the HTML element has been changed. To do so, an event listener is needed.

I don't recomend using value as a variable name, because it can get confused by the .value property to extract the value of an element. In this case I'm using inputNumber instead of value

Try changing the input value so you can see the code in action:

document.getElementById("input").addEventListener('input', function(){
    let inputNumber = this.value
    console.log('your variable value is: '   inputNumber)
})
<header> 
   <input type="number" name="numInput" id="input"  min="0" value="1" required>
</header>

CodePudding user response:

JS objects are the only things in JS that are not cloned in assignment to a new variable. This includes arrays.

Therefore, to mimic the behaviour, you will need to update your value upon every change, typically by adding an event listener. Also, when doing this, the variable can't be of type const, because const variable types can't be changed after they are declared.

const numInput = document.getElementById("input");
let value = numInput.value;

numInput.addEventListener('change', () => {
    value = numInput.value;
});
  • Related