Sucess and error message on form

hi everyone, I’m having a little trouble with my form, the “Sucess” message is not apparing in the screen. Also afte I fill the form it doesn’t clean the fields.

Any help will be much appreciated!

//form

function onSubmit() {

  const name = document.getElementById('name').value

  const email = document.getElementById('email').value

  const phone = document.getElementById('phone').value

  const message = document.getElementById('message').value

  console.log(name, email, phone, message)

 

  const data = {

    name: name,

    email: email,

    phone: phone,

    message: message,

  }

  const url = 'https://otterwise-fake-api.herokuapp.com/contact'

  const stringData = JSON.stringify(data)

  fetch(url, {

    method: 'POST',

    body: stringData,

    headers: {

      'Content-type': 'application/json; charset=UTF-8',

    },

  })

    .then((response) => response.json())

    .then((json) => {

      console.log(json)

      if ((name, email, phone, message === 'name, email, phone, message')) {

        alert('Sucess')

      } else {

        alert('Error')

      }

    })

}

this line makes no sense. What are you trying to check here?

I was trying to create the condition if those fields are complete then send the sucess message

final result:

if (name === '' || email === '' || phone === '' || message === '') {

    return alert('Erro! Complete os campos.')

  }

  const url = 'https://otterwise-fake-api.herokuapp.com/contact'

  const stringData = JSON.stringify(data)

  fetch(url, {

    method: 'POST',

    body: stringData,

    headers: {

      'Content-type': 'application/json; charset=UTF-8',

    },

  })

    .then((response) => response.json())

    .then((json) => {

      console.log(json)

      alert('Sucesso! Pedido enviado.')

      document.getElementById('name').value = ''

      document.getElementById('email').value = ''

      document.getElementById('phone').value = ''

      document.getElementById('message').value = ''

    })

}

[off-topic]
When you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the code block.

I have done it for you this time.
[/off-topic]

1 Like

HTML5 already has that field built into it:

 <input class="passwordBox1" id="passwordBox" type="password" name="user[hashed_password]" value=""
                   tabindex="6" required>

Notice the required attribute, I just put required requirement in the label attribute to let the user know it is required.

1 Like

thank you

1 Like

No probs.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.