JavaScript — Submit Events
I’ve created some basic HTML to give me an input field and a submit button:
The <input type="submit value="submit>
line here gives me a button that, when clicked, will fire off a submit event.
In previous articles I’ve covered setting up event listeners. What I’ve been doing is getting a reference to the object I click and adding a listener to it that looks for a click event. In this scenario, I don’t want to do that. I don’t want to add an event listener to the submit button itself. Instead I want to attach it to the form. That way, when I click the submit button, the form is looking for that event.
Here I’ve gained a reference to the .signup-form
class and added a listener that takes the event data as a parameter. The default behavior for a submit event is to refresh the page. I don’t want the page to refresh.
You can see a super quick flicker there. lol
To stop the page from refreshing I can use this method:
Now if I submit, the page doesn’t refresh.
SO now what?
Lets figure out how to get the data from the form field. In order to do this I need a reference to the username field. Theres a few ways to go about it. Heres one way.
This ('#username)
thing is new. I’m getting this string from the id
I gave the username field in the HTML.
Now, I want to get the data from the input field, so I’ll need to check the input field’s value.
To do that I can simply check the value property. So when I fill in the username field and submit, I’ll get the value of the input field. Like this:
There is an easier way to get a reference to the username though. Since the username is an input that is nested within the form, it can be accessed through dot notation.
This way I don’t need to store a reference to the username in a const.
The next logical step is to check whether the value of the username field is valid or not. In the next article I’ll cover how to do that! See ya there!