edche
edche

Reputation: 680

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}
                />

Upvotes: 0

Views: 549

Answers (2)

Jjagwe Dennis
Jjagwe Dennis

Reputation: 1863

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

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

The react docs have an example too

Upvotes: 1

Duenna
Duenna

Reputation: 2376

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)}

Upvotes: 1

Related Questions