Intro:
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.
[2019-03-06]
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.
Example:
<form id="form-example">
<input type="text" id="input-text" />
<input type="submit" id="input-submit" value="Submit" /> <!-- or <button type="submit">Submit</button> -->
</form>
const form = document.getElementById('form-example');
const text = document.getElementById('input-text');
form.addEventListener('submit', event => {
event.preventDefault();
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 => {
event.preventDefault();
console.log(`Text submitted: ${event.target['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".
References:
- 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)