Search code examples
javascripthtmlreactjsformsonsubmit

Optional fields in the form. How to assign false instead of error?


I ran into an interesting problem. I have a form with optional fields. On submit I get an error trying to assign an empty field to a variable. I want to assign false if the field is empty. How to do it right? Writing multiple ifs seems like a crazy idea to me.

`async function submit(e) {
    const name = e.target.name.value
    const adress = e.target.adress.value
    const comment = e.target.comment.value
}`

i tried like this but still getting error

`async function submit(e) {
    const name = e.target.name.value || false
    const adress = e.target.adress.value || false
    const comment = e.target.comment.value || false
}`

TypeError: Cannot read properties of undefined (reading 'value')


Solution

  • The problem you are having is that either name, address or comment is undefined.

    You can get arround this with optional chaining and nullish coalescing (??):

    async function submit(e) {
        const name = e.target.name?.value ?? false
        const adress = e.target.adress?.value ?? false
        const comment = e.target.comment?.value ?? false
    }
    

    If you use older versions of JavaScript, which doesn't support the mentionend features above, you have to use a more verbose syntax:

    async function submit(e) {
        const name = e.target.name && (e.target.name.value || false)
        const adress = e.target.adress && (e.target.address.value || false)
        const comment = e.target.comment && (e.target.comment.value || false)
    }