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

Time:12-28

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

CodePudding user response:

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

CodePudding user response:

Whether you can use ternary operator or nullish coalescing,

//ternary operator method 
async function submit(e) {
    const name = e.target.name?.value ? e.target.name?.value : false;
    const address = e.target.address?.value ? e.target.address?.value : false;
    const comment = e.target.comment?.value ? e.target.comment?.value : false;
}
//nullish coalescing method
async function submit(e) {
    const name = e.target.name?.value ?? false;
    const address= e.target.address?.value ?? false;
    const comment = e.target.comment?.value ?? false;
}
  • Related