Search code examples
javascripthtmlvariablesevent-listener

How do I add an event listener for a "number" type input in JavaScript?


I'd like to be able to add an event listener to my "number" input in HTML so that when the up arrow is pressed, a variable can be increased by 1, and when the down arrow is pressed, the same variable can be decreased by 1.

I am currently using this:

const strength = document.querySelector('#Strength');
var ability_points = 0;

strength.addEventListener('change', () => {
    ability_points = ability_points+1;
})

Because I am using "change", I cant make it differentiate between the up and down arrows...

I think it very well may be a really simple thing to solve but i just cant find what to make it listen for.


Solution

  • You're best off just using the .value property of the element, rather than keeping track of increments and decrements. If you only handle changes by 1, then you'd get out of sync if the user copied and pasted a totally different number into the field. Try this instead:

    let ability_points = 0;
    
    const strength = document.querySelector('#Strength');
    strength.addEventListener('change', () => {
      ability_points = strength.value;
      console.log(ability_points);
    })
    <input type="number" id="Strength" value="0" />