DEV Community

Cover image for Simple guide for HTML forms
Hildweig 🐬
Hildweig 🐬

Posted on

Simple guide for HTML forms

Introduction

How many websites users visit nowadays that doesn't have some sort of login or interaction with users? Imagine how boring websites would be if the only available content is the website's owner's content (Read-only)? If you couldn't comment nor like, if you didn't have an account, to begin with? HTML forms play a great role in enabling developers to easily create amazing interactive websites where users can purchase products, search for something, participate in surveys, and the list goes on. Now you surely realize how much these elements are necessary and the influence they have on the user experience, this is why you want to have a solid understanding of how to create them, and how to use them.

General idea about forms

In HTML the idea about forms is that you have a bunch of different forms elements available for you, and all of these are wrapped inside a big form container. You can have more than one form in your document, what is important is that your form elements are contained inside a form that serves a particular purpose. And to be able to send what users entered there is also a special element to send the data inside the form. Simple as that!

Alt Text

If you got the idea, let's get started!

1. The form container

Your big form container is the <form></form> element, it has an opening tag and a closing tag, and all your elements are in between. The form element has two attributes that you always need to have:

  • method: The method attribute tells the web browser how to send form data to a server. If you specify a value of POST, this means that the browser will send the data to the webserver. You want to do that if you are sending sensitive data. If the GET method is used, the data is sent inside the URL separated with a question mark. If you want to understand more about these methods I highly recommand you this course.
  • action: your forms are useless unless some kind of processing takes place after submitting. The action attribute helps us to specify where the data will be sent after the submission of the form, the value of the action is a URL. Simply put, after submitting your data will be sent and processed and the next page your user should access is the page that is specified in the action attribute!
<form action="/" method="get">
</form>
Enter fullscreen mode Exit fullscreen mode

2. The form elements

HTML has a plethora of elements for basic things such as entering numbers, text, dates, email, password, as well as more complex elements such as menus, checkable elements, and so much more! Besides, for each of these elements, you can have some sort of validation that is already taken care of. So We have the flexibility to pick what suits us while a part of the troubles for the format etc is already handled.

2.1 The input element

The input element is the most commonly used form element because this element itself can "transform" and have a different behavior according to the type we specify for it to be. Look at this snippet and you will understand:

<input type="an_input_type">
Enter fullscreen mode Exit fullscreen mode

So the shape and behavior and the way you interact with that input are related to the type it has. For the sake of simplicity I will show you the ones you need most of the times:

Input to enter a username:

When you want an input to enter a username, you can specify type="text", type="text" means that your user is allowed to enter any character but it has to be in a single line.

  • If you want to restrict the length to a minimum or a maximum number of characters use minlength and maxlength attributes:
<input type="text" minlength= "2" maxlength="30">
Enter fullscreen mode Exit fullscreen mode
  • If you want to oblige the user to fill that field you can add the required attribute, it just comes as a single word without a value, having it in your input means that it is required, if not then it is an optional field.
<input type="text" minlength= "2" maxlength="30" required>
Enter fullscreen mode Exit fullscreen mode
  • For a good user experience you can add a description about what that input is for, or the expected format, for that you can use the attribute placeholder:
<input type="text" placeholder="Enter username" required>
Enter fullscreen mode Exit fullscreen mode
  • If your field is optional but you still want to have a default value, there is the attribute value, where you specify the default value.
<input type="text" value="UserHasNoName">
Enter fullscreen mode Exit fullscreen mode
  • Of course, all these attributes work for different inputs not only the text type! And I gave you the username as an example, if you need to add a field to enter a single line text then this element is the most appropriate. You can see how these look here (spoiler alert: they won't look like a real form but we will eventually come to that):

Input to enter an email

The input of type "email" is the HTML element you should use for your email fields. It gives us the flexibility to control the format entered and ensure that it is valid, you can specify a minimum and maximum length, consider it required, change the pattern of the input that the email should follow... Just to say that it is perfect! You can also have a default value of course but I doubt you want to do that on a real-world website haha.

<input type="email" placeholder="Enter your email" required>
Enter fullscreen mode Exit fullscreen mode

The way you change the email pattern is by specifying a regular expression, simply put, it is a "string" that can match your text with that string content (like a decoder). If you want to know more about it I highly recommend you this tutorial. And by the way, this attribute pattern also works for the input type of text, imagine if you have a country code with a specific pattern, this attribute is just perfect for more validation!

<input type="email" placeholder="Enter your email" pattern= "your regular expression here" required>
Enter fullscreen mode Exit fullscreen mode

Input for your passwords

The input of type="password" is a single text input that masks the characters for you while your user is typing (no need for extra-work to make it like that!). Same as for the email you don't want to have that field empty so I highly recommand you to use the required attribute, and most of the type you would find passwords of a minimum length of 8 characters, you can also add the maximum length attribute in case you have some troller that would type 999 characters as a password.

<input type="password" placeholder="Enter your password" minlength="8" maxlength="50" required>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Input for numbers fields

If you want to ensure that the user can only enter numbers, use the input type="number".

  • The input type number has two nice attributes: min, and max, if your field concerns age and you don't want to have negative values then you can put the min ="0", same, for age if you want to have a maximum value that user can't exceed, you can add a default value with value ="your value", and make required if you want to and even have a placeholder, all what's available for inputs is available!
<input type="number" min="0" required placeholder="enter age">
Enter fullscreen mode Exit fullscreen mode

Alt Text

  • You can see that there is arrows, when you click on them you either add (+1) starting from 0 if you click on the upper arrow, or (-1) if you click on the other arrow, of course you can change how much you want to increase/decrease by specifying an attribute called step. You add it to your input and specify how much you want to "step". If I want to increase my values with 10 each time, then step="10", but once you reach the minimum you can't go bellow if min is specified, same for the max.
<input type="number" min="1" required placeholder="Enter quantity" step ="10">
Enter fullscreen mode Exit fullscreen mode

Input for dates

You've probably guessed it, your input will have the type "date". Users will be able to enter the date either from a calendar that shows up as an icon or from a textbox. Say you are having a hotel website and your users can reserve rooms for some time, one of the things you would probably need is to restrict dates, it's weird if someone can reserve for yesterday, so same as the number input, you have a min and max attributes, excepts this time these are dates that follow this format: "yyyy-mm-dd".
Here is an example:

<input type="date" 
       value="2021-02-07"
       min="2021-01-07" max="2021-12-31">
Enter fullscreen mode Exit fullscreen mode

Alt Text
The picture on the left is how it looked when I clicked on the year to change it, pretty nice right? I also added a default value assuming the reservation is for today in case the user doesn't change it.

Input for files!

Yess, who guessed that we can upload files that easily! Just have the input with type="file" and your users will be able to enter files in the field. You can also add the attribute multiple to be able to enter multiple files at the same time in the same field, it comes just as a single word, and having it there means that the multiple selection is activated. Also, you can restrict the types of files users can enter, if there is more than one then you can just separate them with commas (,).

<input type="file" accept=".doc,.docx,.txt" multiple>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Input for searching

The search bars we see on websites are created using the input type="search", you can add a placeholder, a minlength or a maxlength if you want to, anyways here is an example!

<input type="search" placeholder="search">
Enter fullscreen mode Exit fullscreen mode

Alt Text

Input for choosing colors

This one I found it twice or so on a website where the owner showed a beautiful Pomodoro with a cat and you can change the cat color and the background, it was pretty cool so even if it's not used that much I thought "why not?", you can add a default value using the value attribute if you want to. Here is how you can add a field to select colors:

<input type="color" value="#A5D9D6">
Enter fullscreen mode Exit fullscreen mode

Alt Text

Checkboxes

Checkboxes look like squares that users can "check". Let's say you have a list of toppings that clients can include in their pizza. They can select one or multiple toppings at the same time using checkboxes, and for each one, you would have something like this:

<input type="checkbox" id="mushrooms" name="topping">
<label for="mushrooms">Mushrooms</label>
Enter fullscreen mode Exit fullscreen mode
  • The first line is the input element, this is precisely our checkbox.
  • Since you can't have any text with it (not even a placeholder), you need a way to show what that checkbox represents, and we do that using an element called "label". Most of the time, form elements are associated with a label element. The attribute "for" will link with the element by having the same value as the id attribute in the input. Besides, not only they are visually linked, but they are programmatically associated with it too. Another advantage is that, when you click on the label, you will automatically activate/focus on the input as well. If your users use a touch screen device, this will make things a little bit easier for them.
  • The name attribute will help us to identify the data we send to the server. In fact, in all your form elements you should always add the name attribute, I left it up to now to not condense the information, but now you know that in your elements you would have an id and a name too. The value of the name attribute can't be an empty string and should be unique, but for checkboxes, they can be the same.
  • The id and name can have the same value, but each id should be unique with other ids, same for the name attribute.
  • There is an attribute called "checked", that you can specify if to have a checkbox checked by default. Here is another example with two checkboxes:
<form method="post" action="/">
  <input type="checkbox" name="topping" id="cheese" checked>
  <label for="cheese">Cheese</label>

  <input type="checkbox" name="topping" id="mushrooms">
  <label for="mushrooms">Mushrooms</label>

  <input type="checkbox" name="topping" id="olives">
  <label for="olives">Olives</label> 
</form>
Enter fullscreen mode Exit fullscreen mode

If you noticed, I have the same name, since later since they are about toppings, I can get the values programatically in a list by using that name, so all my toppings selected would be extracted at once. But the ids are different.
Alt Text

Radio buttons

Radio buttons are useful when you want your user to select only one option. Here too, the name for each radio button is the same but the ids are different. And you can also have the checked attribute to have one checked by default. To create a radio button, you specify the value "radio" in the type attribute:

<form method="post" action="/">
  <input type="radio" name="gender" id="male">
  <label for="male">Male</label>

  <input type="radio" name="gender" id="female" checked>
  <label for="female">Female</label>

  <input type="radio" name="gender" id="other">
  <label for="other">Other</label> 
</form>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Note that if you have other radio buttons with another name, it won't be a problem, the "only one" concerns radio buttons with the same name.

Other input types

The list of types that exist is so long so I don't want to kill you with new information, the ones I showed you are the most used inputs but if you are curious about other types here is a list, hope it will help you! Also, you don't need to push yourself to remember them immediately, it will come with time and practice, the more you use them, the more you'll remember them, worst case Google is your friend!

Submitting your form

Now that you have a bunch of input elements you can use inside your form it's time to show you how you can submit your data and send it to the server. There is an specific type of input called "submit" that allows us to exactly do that. By default the word is "Submit" but if you want to change it, you can do it by entering the word you want to display with the attribute value:

<input type="submit" value="Send">
Enter fullscreen mode Exit fullscreen mode

2.2 The button element

While the input of type submit is always found inside forms, buttons can be found anywhere in an HTML document. In our case, we're only interested in using it inside the form to send our data. To do that, we add to the button the type attribute with the value of submit.

<button type="submit">Submit</button>
Enter fullscreen mode Exit fullscreen mode

The main advantage of having a submit with a button instead of input is that you can create a more complex component, it can have an icon, and more if you want, while the input can have only the text it has in the value attribute.

2.3 Textarea element

We saw earlier that <input type="text"> allows us to enter a single line text. Now we want to be able to enter a real text with multiple lines. The <textarea><textarea> element comes with an opening tag and a closing tag, you can specify in advance the text by putting it in between, or leave it like that for the user to enter their content.

<label for="comment">Comment</label>
<textarea name="comment" id="comment" rows="10" cols="30">
</textarea>
Enter fullscreen mode Exit fullscreen mode

The size of this textarea is determined by the number of rows and columns it can have (a bit weird for the columns but, it is what it is). Here are some useful attributes you can use:

  • maxlength: the maximum number of characters allowed.
  • placeholder: so tat you can describe the expected content.
  • required: if you want to ensure that it won't be left empty.

2.4 Menu options

Many pages have some sorts of menus where you select one of the options. Let's say you're registering into a website and they ask you to specify your country among a list of countries. This is done by using the <select></select> element, associated with a list of <option></option> elements inside.

<label for="countries">Choose a country:</label>
<select name="countries" id="countries">
  <option value="">Country</option>
  <option value="frontend">Front-end Land</option>
  <option value="backend">Back-end Land</option>
  <option value="fullstack">Full Stack Land</option>
</select>
Enter fullscreen mode Exit fullscreen mode

Here I have my label, for and id have the same values to associate the label and the select element. And inside I have a list of options. The text in between is so that it will be displayed on the page, and the value attribute holds the data that will be sent to the server. So when a user clicks on an option, it's the value that will be sent not the text in between.
Alt Text
Now here is a cool trick, what if you want a user to choose their nationality, but they have two? With select, we can create multiple groups of options, and in each group you can pick an option. For that we need another element: <optgroup></optgroup> and the optgroup has the attribute "label" that can be used ti describe each group! Inside each <optgroup> you would have your options.
Alt Text
Here is an example:

<label for="nationalities">Choose a car:</label>
<select  name="nationalities" id="nationalities">
  <optgroup label="First nationality">
    <option value="dreamer">Dreamer</option>
    <option value="worker">Worker</option>
  </optgroup>
  <optgroup label="Second nationality">
    <option value="morning person">Morning person</option>
    <option value="night person">Night person</option>
  </optgroup>
</select>
Enter fullscreen mode Exit fullscreen mode

Alt Text

Wrap up

With all that, let's create a form for registration:

And here is a small summary about all what you've learned:

  • HTML forms allow us to have a better user experience on our websites.
  • All HTML forms have a <form></form> element as a parent.
  • Our elements are nested inside the <form></form> element.
  • There are multiple elements that can be used: inputs (for email, username, date, numbers...etc), buttons (to send our data), textarea (to enter a text), select (to create menus).
  • You can select multiple checkboxes while you can select only one radio button in a form as long as the radio elements have the same name.
  • We can have more complex menus using <optgroup></optgroup>

Thank you

Once again I am so happy that you've read up to this point! If you have a dream, don’t just sit there. Gather courage to believe that
you can succeed and leave no stone unturned to make it a reality. All your efforts are worth it, looking forward to see how you will shine in the future! If you liked this post please like and share, and if you have any question feel free to ask and I will gladly answer! See you soon!

Top comments (0)