0

I have a Material UI form which I am disabling the submit button until all fields are filled out, The problem is, some of the fields in the form may need to have a "0" value, but if you simply type in a "0" it won't accept it as a value. If you type anything after the 0 it will accept the value and enable the button. What am I doing wrong and how can I correct this?

const disabled = (!values.name || !values.avgRunTime || !values.avgSetupTime);


    const handleInputChange = e => {
        const { name, value } = e.target;
        setValues({
            ...values,
             [name]: ( typeof value === 'string' ? (value).replace(/ +(?= )/g, '').trimStart() : value ) 
        });
    };


    <Form onSubmit={handleSubmit} >
           <Input
                type='text'
                onChange={handleInputChange}
                name='name'
                label='Name'
                value={values.name}
           />

           <Input
               type='text'
               onChange={handleInputChange}
               name='avgRunTime'
               label='Avg. Run Time'
               value={values.avgRunTime} 
          />

          <Input
               type='text'
               onChange={handleInputChange}
               name='avgSetupTime'
               label='Avg. Setup Time'
               value={values.avgSetupTime}
          />

          <Button
              type='submit'
              text='Submit'
              onClick={handleSubmit}
              disabled={disabled}
          />
      </Form>
    );
}

!values.*** should only disable the button if the value is null or undefined, correct? 0 should count as in value, since it has been typed in, right?

Mtullis
  • 117
  • 9

1 Answers1

3

0 is falsy in JavaScript, so it will evaluate disabled to true:

const values = {
  name: "Something",
  avgRunTime: 2500,
  avgSetupTime: 0
}

const disabled = (!values.name || !values.avgRunTime || !values.avgSetupTime);

// false
console.log(`name: ${!values.name}`);
// false
console.log(`avgRunTime: ${!values.avgRunTime}`);
// true
console.log(`avgSetupTime: ${!values.avgSetupTime}`);
// true
console.log(`disabled: ${disabled}`)

Instead, it's probably best to have the unset value be null (source), and do a null check (=== null) instead of a falsy check.

Jeff
  • 2,425
  • 1
  • 18
  • 43
  • Jeff, that is a good idea. I also thought about changing it to something like "values.avgSetupTime.length < 1". That was it would recognize the 0 as a character. – Mtullis May 23 '23 at 14:11