Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  126] [ 4]  / answers: 1 / hits: 9312  / 4 Years ago, tue, april 14, 2020, 12:00:00

I have an <input> tag of type=number, and I would like to disable keyboard input in order to force the user to change the value with the spinner (up and down arrows). I am consuming the input value on every change, so I want to do this so that I don't have to validate user input in real-time, which seems like the only alternative.



Outside of vanilla html and javascript, I would also like to know how to do this in react and material-ui. If I have something like the following, how can I prevent keyboard input?



  const [value, setValue] = useState(10);

return (
<React.Fragment>
<TextField
name=name
type=number
label=label
inputProps={{
min: 0,
max: 100,
step: 2,
}}
defaultValue={value}
onChange={(event) => {
setValue(Number(event.target.value));
}}
/>
</React.Fragment>
);

More From » html

 Answers
2

This seems like a basic question, but I was surprised to not be able to find the answer anywhere, so I'm providing one here.


The key in both cases is to capture the onkeydown event and run its method preventDefault().


Vanilla HTML and javascript


  <input type="number" min="0" max="100" step="2" value="10"
onkeydown="preventKeyboardInput(event)" />

<script>
function preventKeyboardInput(event) {
event.preventDefault();
}
</script>

React


  <input
type="number"
min={0}
max={100}
defaultValue={10}
step={2}
onKeyDown={(event) => {
event.preventDefault();
}}
/>

Material-UI


Material-UI's <TextField> is a wrapper around react's <input>, so all you need to do is pass onKeyDown down via inputProps, which you are already using to pass min, max, and defaultValue.


  const [value, setValue] = useState(10);

return (
<React.Fragment>
<TextField
name="name"
type="number"
label="label"
inputProps={{
min: 0,
max: 100,
step: 2,
onKeyDown: (event) => {
event.preventDefault();
},
}}
defaultValue={value}
onChange={(event) => {
setValue(Number(event.target.value));
}}
/>
</React.Fragment>
);



UPDATE: I've discovered roundabout that this breaks input boxes on touch devices, or at the very least iOS and iPadOS, neither of which display or allow input from spinners, which is probably why it was downvoted in the first place. Caveat emptor for anyone wanting to use this method.


[#4170] Saturday, April 11, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
austonjuancarlosb questions
;