-1

Hey Everyone and thank you for your time. I have a problem to submit a form in JS. Obviously my form has the value "null", but i don't can figure it out why. Can you help me, im new to JS.

HTML:

<form id="form">
  <input type="text" id="username" placeholder="Username" required>
  <input type="email" id="email" placeholder="Email" required>
  <input type="submit" value="Register">
</form>

JS:

var form = document.getElementById('form')

form.addEventListener('submit',function(event){
  event.preventDefault()

  var username = document.getElementById("username").value
   console.log(username)
    
      var email = document.getElementById("email").value
      console.log(email)
    })

Error Massage: Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

3
  • How are you loading/running your Javascript? Make sure to wait until the DOM is loaded, i.e. using the DOMContentLoaded event. Commented Dec 2, 2021 at 22:54
  • Hmm, how are you executing the JS in your HTML page? Can you show your entire HTML? Commented Dec 2, 2021 at 22:54
  • When a form submits, the name attribute of the element is used, and your elements don't have names. That could cause an issue with your ability to retrieve the data on the server side, if you're submitting the form through the default submit action. It's not clear to me from your question exactly how you are submitting the form. Commented Dec 2, 2021 at 23:02

1 Answer 1

-1

Please make sure you are loading your html first like so:

<body>
  <form id="form">
    <input type="text" id="username" placeholder="Username" required>
    <input type="email" id="email" placeholder="Email" required>
    <input type="submit" value="Register">
  </form>
  <!--Javascript-->
  <script>
    var form = document.getElementById('form')

    form.addEventListener('submit',function(event){
      event.preventDefault()

      var username = document.getElementById("username").value
      console.log(username)
    
      var email = document.getElementById("email").value
      console.log(email)
    })
  </script>
</body>

Other than that it looks fine.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.