简体   繁体   中英

How to disable form submit button until all input fields are filled in ReactJS?

I want to send a form so I created a function for that. I have a submit form, and the button should not enable until all fields of the form are fully filled.

All validations are working but this is not a problem, I need it for an onclick event.

My code works but when I click the checkbox one time to make it true and click again to make it false, the button should be disabled , but again it will be enabled. ...

const [name, setName] = useState("");
  const [surname, setSurname] = useState("");
  const [email, setEmail] = useState("");
  const [checkbox, setCheckbox] = useState(false);
  let handleSubmit = async (e) => {
    e.preventDefault();
    try {
      ...
    }
  };
return(
<Input
                      required
                      type="text"
                      value={name}
                      placeholder="İsim"
                      onChange={(e) => setName(e.target.value)}
                    />
<Input
                      required
                      type="text"
                      value={surname}
                      placeholder="Soyisim"
                      onChange={(e) => setSurname(e.target.value)}
                    />
<Input
                      required
                      type="email"
                      placeholder="E-mail"
                      onChange={(e) => setEmail(e.target.value)}
                    />
<Input
                      type="checkbox"
                      required
                      value={checkbox}
                      onChange={(e) => setCheckbox(e.target.value)}
                    />
<input
                  type="submit"
                  name="Onaylıyorum"
                  disabled={!name || !surname || !email || !checkbox}
                />

Checkboxes are special and don't have a .value , rather, you want to be looking for .checked in your checkboxes onChange function.

Like this...

onChange={(e) => setCheckbox(e.target.checked)}

For the checkbox you have to change from value prop to the checked prop and access event.target.checked instead ie

 <input type="checkbox" checked={checkbox} onChange={(e) => setCheckbox(e.target.checked)} />

The react docs have an example too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM