JS3
JS3

Reputation: 1847

How to remain the textfield to 0? Clearing up the textfield will cause another value to isNaN

If I leave this as a blank field, this will cause the total to display as isNaN and I don't want the form to be submitted if it is an isNaN. How do I prevent the form from being submitted if the total value shows as isNaN?

export default function BasicTextFields() {
  const [fee, setFee] = useState(0);
  const amount = parseInt(1000);
  const total = Number(amount) + Number(fee);
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(" submit");
  };
  return (
    <form onSubmit={{ handleSubmit }}>
      <TextField
        label="Fee"
        type="number"
        value={fee}
        onChange={(e) => setFee(parseInt(e.target.value))}
        InputProps={{
          inputProps: {
            min: 0
          }
        }}
      />
      <button type="submit">Submit</button>
      <br />
      Total: {total}
    </form>
  );
}

codesandbox: https://codesandbox.io/s/basictextfields-material-demo-forked-7sfdph?file=/demo.js:171-809

Upvotes: 1

Views: 519

Answers (2)

Different Fun
Different Fun

Reputation: 1

import React, { useState } from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";

export default function BasicTextFields() {
  const [fee, setFee] = useState(0);
  const amount = parseInt(1000);
  const total = Number(amount) + Number(fee);

  // async is not required if you are not using await keywork in function.
  const handleSubmit = (e) => {
    e.preventDefault();
    if (isNaN(fee)) {
      console.log("its not a number");
    } else {
      console.log("its a number");
      
      // this submit will refresh page.
      // e.target.submit();


      // if you do not want page to refresh.
      // remeber there is different approch for image data.
      var formData = new FormData();
      formData.append('fee', fee);
      console.log(formData);
      // continue with sending data to your backend server
    }
  };

  const changeFee = (e) => {
    setFee(e.target.value);
  }
  return (
    // use only one curly braces
    <form onSubmit={handleSubmit}>
      <TextField
        label="Fee"
        type="text"
        value={fee}
        onChange={changeFee}
        InputProps={{
          inputProps: {
            min: 0
          }
        }}
      />
      <button type="submit">Submit</button>
      <br />
      Total: {total}
    </form>
  );
}

read the all comments mentioned in above code maybe it helps.

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

You can use

 onChange={(e) => {
          if(e.target.value===""){
            setFee(0);
          }else{
          setFee(parseInt(e.target.value))}}
        }

Upvotes: 2

Related Questions