简体   繁体   中英

Checkbox do not save value if not checked/unchecked

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

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}

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