2

I am trying to validate a Number Input field in Javascript.

Issue is, when I use mouse wheel to change the value I am unable to validate it correctly.

If current value is 5, and i do a scroll up with mouse wheels, current value is being displayed as 5, not as 6. It seems the mouse event is being triggered at the start of the event. Hence it still has the old value.

<label>Choose an ice cream flavor:
    <input type="number">
    <p></p>
</label>
<script>
var inputc = document.querySelector('input');
var pc = document.querySelector('p');
inputc.addEventListener('wheel', function (e){
  pc.innerText = 'The value is ' + inputc.value;
});
</script>

Link to jsfiddle: https://jsfiddle.net/3o8g7cdy/1/

Any Idea on how to validate for this correclty. Thanks.

Gowtham Raj J
  • 937
  • 9
  • 26

1 Answers1

7

You can listen for input event instead of wheel.

var inputc = document.querySelector('input');
var pc = document.querySelector('p');
inputc.addEventListener('input', function (e){
  pc.innerText = 'The value is ' + inputc.value;
});
<label>Choose an ice cream flavor:
    <input type="number">
    <p></p>
</label>

Additional Information: If you still want to use wheel event, you may add some delay to value changing operation. Even setTimeout(function(){}, 0) will solve problem. How?

<label>Choose an ice cream flavor:
    <input type="number">
    <p></p>
</label>
<script>
var inputc = document.querySelector('input');
var pc = document.querySelector('p');
inputc.addEventListener('wheel', function (e){
 setTimeout(function(){ pc.innerText = 'The value is ' + inputc.value;},0);
});
</script>
Tuğca Eker
  • 1,493
  • 13
  • 20