Background
When submitting a numeric price input, I noticed the value wasn’t the same as what I originally typed. I thought there was something wrong with my code configuration. Later, I realized that if a number input field is still focused, scrolling with the mouse can change its value.
I find this default behavior problematic—it can easily lead to user input errors. So, I looked for a way to disable it.
My project is built using Next.js and TypeScript.
In the video below, you’ll see the first field allows value changes when it’s focused and I scroll up/down. The second field has the fix applied, so scrolling no longer changes the value.
How to Prevent Scroll from Changing the Number Input Value
Add this function to your component:
1const numberInputOnWheelPreventChange = (e: WheelEvent<HTMLInputElement>) => {
2 const target = e.target as HTMLInputElement; // Type assertion
3 // Prevent the input value from changing
4 target.blur();
5
6 // Prevent page/container scrolling
7 e.stopPropagation();
8
9 setTimeout(() => {
10 target.focus();
11 }, 0);
12};
Then attach it to your number input via the onWheel event:
1<Input
2 type="number"
3 id="nonPeakHourPrice"
4 placeholder="Enter the price for non-peak hours."
5 className="text-sm"
6 {...register("nonPeakHourPrice")}
7 onWheel={numberInputOnWheelPreventChange}
8/>