Skip to content Skip to sidebar Skip to footer

Input Type Number: How To Detect If Value Was Incremented Or Decremented?

Up until now, I simply used 'change' to see if an input field of the type 'number' was changed. However, now I need to know if the number was incremented or decremented to perform

Solution 1:

You could simply previously store the value of your input and compare it on change :

let value = $('#test').val();

$('#test').on('change',function(){
  if($(this).val() > value){
    console.log('Input was incremented');
  }else{
    console.log('Input was decremented');
  }
  
  value = $(this).val();
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="number"id="test"value="0">

Solution 2:

You'll want to make use of a variable outside of your change function to keep track of the last value that was entered. Inside of your change function, simply compare against this value to find out whether the new value is higher or lower. Don't forget to update the previous value after the check!

This can be seen in the following:

let previous_value;

document.getElementById("input").addEventListener("change", function() {
  let value = document.getElementById("input").value;
  if (previous_value > value) {
    console.log("Decreased");
  } elseif (previous_value < value) {
    console.log("Increased");
  }
  previous_value = value;
});
<inputtype="number"id="input">

Solution 3:

Along with the suggestions made of storing the previous value in memory in the JS, you could also store it on the input element itself, as a data attribute. That way JS from anywhere in your application will know the previous value, without having to have access to a variable

<input class="spinner"type="number" data-prev-value="0" />

$('.spinner').on('change', (e) => {
  let direction = e.target.value > parseInt(e.target.dataset.prevValue) ? 'up' : 'down'
  e.target.dataset.prevValue = e.target.value;
  console.log(direction);
})

Solution 4:

Whilst the answers above do what the OP requested, it is also worth noting that the input field of type "number" can be changed by user input as well as by the arrows. Hence, although you know the direction, you will not neccessarily know how much the item has been incremented or decremented. This function will show a positive or negative number (so doing what the OP requested) but also show the amount incremented or decremented:

let value = $('#test').val();

$('#test').on('change', function() {
    change = $(this).val() - value;
    value = $(this).val();

    console.log(change);
});

Post a Comment for "Input Type Number: How To Detect If Value Was Incremented Or Decremented?"