Checkbox do not save value if not checked/unchecked

Viewed 45

I have a form with checkbox inputs. If the checkbox is not checked or unchecked by hand, it will not save the value in the submit handling.

this is the checkbox input field:

const CheckBoxField = ({ name, placeholder, isChecked, handleChange }) => {
    return (
<div class="input-div">
<label>{name}</label>
      <input
        type="checkbox"
        name={name}
        placeholder={placeholder}
        defaultChecked={false}
        value={false}
        onChange={handleChange}
      />
    </div>
);}

export default CheckBoxField;

and here i am using the chechbox component:

 if (input[form].input_type === "checkbox") {
                    return (
                      <CheckBoxField
                        name={input[form].name}
                        placeholder={input[form].placeholder}
                        required={input[form].required}
                        key={input[form].placeholder}
                        isChecked={true}
                        handleChange={handleChange}
                      />
                    );
                  }

and my handlechange function:

  const handleChange = (event) => {
    console.log(event.target.name, event.target.value)
    const inputs =
    event.target.type === "checkbox" ? event.target.checked : event.target.value
    setValue({ ...value, [event.target.name]: inputs });
  };

I do not understand what i am missing. I have a defaultChecked to false, which should be the one that set a value if none is chosen, or what?

please help me

1 Answers

Because the property: name, value, type, checked, do not exist in the target object. Use currentTarget instead of target, then the properties will be defined.

const [value, setValue] = useState();

const handleChange = (event) => {
    //console.log(event.currentTarget.name, event.currentTarget.value)
    const inputs =
        event.currentTarget.type === "checkbox" ? event.currentTarget.checked : event.currentTarget.value
    setValue({ ...value, [event.currentTarget.name]: inputs });

};

useEffect(() => {
    console.log(value);
}, [value])
logs:
> {onChange: true}
> {onChange: false}
Related