Tips on getting data from HTML forms

Hey everyone, today I want to share with you something that quite a number of Javascript beginners get wrong while getting data from a form.

Let's get started😁

Here is a signup form that we want to submit to somewhere cool😎 on the backend because programmers do only cool things😏.

<form action='<somewhere-cool>' id='signupForm'>
  <input 
     id='name'
     type='text' 
     name='name' 
     placeholder='Name' />
  <input 
     id='password'
     type='password' 
     name='password'  
     placeholder='Password' />
  <input 
     id='confirmPassword'
     type='password' 
     name='confirmPassword' 
     placeholder='Confirm password' 
  />
 <button>Sign up</button>
</form>

Looking at the form, I would argue there are at least 3 ways to retrieve the values in the form. So now let's look at one way to do this (a bad way👎🏿)

<script>
  document.getElementById('signupForm').onsubmit = (event) => {
    event.preventDefault();
    const userName = document.getElementById('name').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    //DO SOME VALIDATION AND THE OTHERS

    //Do SOME AJAX STUFF
}
</script>

this will be at the bottom of the body tag

I see this as a bad method because you would be making unnecessary calls to the DOM (Document Object Model) and also it becomes kinda stressful when you have multiple inputs in the form.

Here is a way I think is better and of course cooler😎

const $signupForm = document.getElementById('signupForm')
$signupForm.onsubmit = (event) => {
    event.preventDefault();
    const userName = $signupForm['name'].value;
    const password = $signupForm['password'].value;
    const confirmPassword = $signupForm['confirmPassword'].value;

    //DO SOME VALIDATION AND THE OTHERS

    //DO SOME AJAX STUFF
}

This is possible because a form can be seen as a collection of inputs (like an associative array), whereby the keys are the names of the input and values are well is the input elements.

You can also try something like this, although it does not work for all input depending on the name

 const userName = $signupForm.name.value;
 const password = $signupForm.password.value;
 const confirmPassword = $signupForm.confirmPassword.value;

Using the dot (.) notation wouldn't work when the input name contains a hyphen or underscore

<input id="matric-no" name="matric-no" type="text"/>

That'll be all for today

Comments (1)

Inu John's photo

Thanks a lot for this🙂