Building forms is a common task in front end. In this exercise, we will build a basic "Contact Us" form, commonly seen on marketing websites for visitors to ask questions or provide feedback.
<textarea> will be more suitable.Upon submission, POST the form data to https://questions.greatfrontend.com/api/questions/contact-form with the following fields in the request body: name, email, message.
If all the form fields are correctly filled in, you will see an alert containing a success message. Congratulations!
You do not need JavaScript for this question; the focus is on HTML form validation and submission.
This is a basic question that evaluates your knowledge of the web platform. Forms and form submissions can be built entirely without any JavaScript! As a Front End Engineer, it's important to know what the platform provides and not resort to JavaScript for everything.
The first thing we need to do is wrap the fields in a <form>, which is already given in the template. To tell the <form> which URL to submit the data to, we use the action attribute with the API URL as the value. The API URL expects an HTTP POST request, hence we also use method="post" on the <form>.
For form fields with the name attribute, the attribute value becomes the key in the form data. Hence we can add name="name", name="email", and name="message" to the various form fields. Also add <label>s to label your <input>s.
Lastly, submit buttons can be implemented in two ways:
<button type="submit">: By default, <button>s have type="submit", and when used in <form>s, they will trigger a form submission.<input type="submit">: The element will be rendered as a button and clicking the <input> will trigger a form submission.<textarea>, which will add a new line).<label>s to <input> so that clicking on the <label> will focus on the corresponding <input>.
<label for="some-id"> and <input id="some-id"> to define the relation between <label> and <input>.<input> inside of <label> because some assistive technologies (e.g. Dragon NaturallySpeaking) do not support it.Now that you are familiar with form submission, try out a follow-up question, Signup Form, where you will be asked to make an AJAX-based form request and perform client-side validation.
<!doctype html><html lang="en"><head><meta charset="UTF-8" /><metaname="viewport"content="width=device-width, initial-scale=1.0" /></head><body><div id="root"></div></body></html>
console.log() statements will appear here.