DEV Community 👩‍💻👨‍💻

Cover image for What I've learnt in web dev today [1]: "Form submission"
Islam Sayed
Islam Sayed

Posted on

What I've learnt in web dev today [1]: "Form submission"


Everyday I face issues, encounter unknown things, meet bugs, search for solutions, and finally I learn new stuff. I think that it would be useful to write what I've learnt everyday. It may help someone else who is willing to know such things, or just want quick hints and brief info.


Event listener for form submission.

  • I ran into an issue today when I wanted to listen to submit event of a form.
  • I thought that I should add the event listener to the <input type="submit" />, or <button type="submit"></button>, where I was supposed to do the action (click to submit the form). I was wrong!
  • The concept is that when I click the submit button, I submit the form not the button. So it makes sense that the event listener is added to the form itself not the submit button.


<form id="form-example">
  <input type="text" id="input-text" />
  <input type="submit" id="input-submit" value="Submit" /> <!-- or <button type="submit">Submit</button> -->
const form = document.getElementById('form-example');
const text = document.getElementById('input-text');
form.addEventListener('submit', event => {
    console.log(`Text submitted: ${text.value}`)
  • I also found out that you can get the value of <input type="text" /> via the event target in this way.
form.addEventListener('submit', event => {
    console.log(`Text submitted: ${['0'].value}`)
  • This is because event target <form> is an is a reference to the object that dispatched the event with its children as properties. And each property key is a number starting from "0".


  • That's it for today. Please, write ✒️ me a comment telling me if I should continue this series, or not. And of course, correct me if I was wrong in any thing.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!