3

I'm using MUI type="number" textfields, but when I focus it and then scroll the mousewheel, the value of the input changes. I've read about adding blur after scroll, but I don't want to blur the field.

I've read too about adding blur and focus again, but the behaviour isn't good enough.

Could somebody help me? Thanks a lot! :)

I'm using React v18 & MUI v5.

To reproduce this behaviour, you can go to https://mui.com/material-ui/react-text-field/, click in a type number textfield, and then scroll OVER the field. You will see how the value changes.

I've tried using blur and focus, but this behaviour is not good enough

2
  • I can't reproduce that behaviour here mui.com/material-ui/react-text-field
    – Konrad
    Commented Dec 19, 2022 at 19:29
  • Please provide enough code so others can better understand or reproduce the problem.
    – Community Bot
    Commented Dec 19, 2022 at 20:18

4 Answers 4

1

I had this issue with SurveyJS, here are 2 ways to solve it below!

const scrollableElements = 
 document.querySelectorAll('input[type="number"]');
    scrollableElements.forEach((item: HTMLElement) => {
      item.addEventListener("wheel", (e: any) => {
    e.preventDefault();
    return false;
  });
 });

const scrollableElements = 
 document.querySelectorAll('input[type="number"]');
 scrollableElements.forEach((item: HTMLElement) => {
  item.setAttribute("onwheel", "return false");
 });
1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Mar 13, 2023 at 16:54
0

The best solution is to use a type={'text'} TextField and then add inputProps that exclude non-numeric inputs

<TextField inputProps={{ inputMode: 'numeric', pattern: '[0-9]*' }} />

As shown in the MUI docs: https://mui.com/material-ui/react-text-field/

1
  • Where are you getting 'pattern' from? I don't see it anywhere in the documentation you linked, or the documentation for the Input component.
    – Mike G.
    Commented Oct 21, 2024 at 14:58
0

You can disable the mouse wheel scrolling over a type "number" input in React by using the following piece of code. It will also prevent the default behavior for the up and down arrow keys.

const handleKeyDown = (e: any) => {
    if (e.key === "ArrowUp" || e.key === "ArrowDown") {
      e.preventDefault();
   }
};

<input
  type="number"
  onKeyDown={handleKeyDown}
  onWheel={(e) => e.target.blur()}
  // other props...
/>
-1

Use onKeyUp instead of onChange onKeyUp not fire with you scroll the mouse

 onKeyUp={(e) => {
     console.log(e.key)
     console.log(e.target.value)
 }}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.