I have few input fields few are type text and few are type checkboxes how can i get all the fields value together right now i'm able to only one at a time like given below example:-
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
this.setState({ [event.target.name]: event.target.checked });
};
I'm not able to use both together. Whats wrong with it?
Thank you for your efforts!
You could use nullish coalescing operator :
this.setState({ [event.target.name]: event.target.checked ?? event.target.value });
Or explicitly test for the property existence:
if('checked' in event.target) {
this.setState({ [event.target.name]: event.target.checked });
}
if('value' in event.target) {
this.setState({ [event.target.name]: event.target.value});
}
You could have a conditional statement depending on the input type property. The checked
property is only used with <input type=checkbox />
this.setState({ [event.target.name]:
event.target.type === 'checkbox'
? event.target.checked
: event.target.value
});
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.