Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change value via input and buttons simultaneously

I have an input field that takes numbers and i want to change the value by keyboard input but also via buttons.

The buttons work fine as long as I don´t use keyboard input.
If I type in 10 for example and add 1 with the button the value changes to 101 and not to 11 as I expected. On the other hand, when I decrement the value with the button it works correctly again.

How can I make it work correctly?
I would be grateful for your help…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const [maxAmount, setMaxAmount] = useState(0);

const decrementMaxAmount = () => {
    if (maxAmount > 0) setMaxAmount(maxAmount - 1);
  };

const incrementMaxAmount = () => {
    setMaxAmount(maxAmount + 1);
  };

<button onClick={() => decrementMaxAmount()}>
<button onClick={() => incrementMaxAmount()}>

<input
 type="number"
 name="maxAmount"
 value={maxAmount}
 onChange={(event) => setMaxAmount(event.target.value)}
/>

>Solution :

Type of event.target.value is a string. So your maxAmount is a string :
maxAmount + 1 === "10" + 1 === "101".

To avoid this, you can convert your type with the Number() constructor :
setMaxAmount(Number(event.target.value))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading