Blog

Web Design Course for Beginners: Form Element

Web Design Course for Beginners: Form Element 1

The form element is used to create a container for collecting feedback from users. It cannot stand on its own without other form controls. This tutorial teaches how to work with forms in HTML.

So far, we have discussed the structure of an HTML5 webpage, looked at elements and their categories. We further looked at attributes and how to use them. To illustrate how these elements work in a browser, we looked at some basic elements under the headings: block-level and inline-level elements. In these considerations, we did not mention the form element.

Most of the elements discussed are static in nature, except for few that allow users to interact.

What if you want feedback from users, such as; wanting them to submit their personal data, or comment on a post or even contact you for product support. In these cases, we need a means of getting this information, but how? By using the form element.

In this module, we are going to deep dive into how to use the form element to create a form in your webpage. We will also look at the form input elements and their types.

Form Builder Elements

The Form Element <form>

The form element is used to create user interaction using form controls. These form controls are used to collect information from users.

What is a form in HTML?

A form is an element in HTML5 that contains input controls and attributes. These controls are used to collect, validate and submit user information to the form owner. This information may include the name of users, email address, and comments. The type of input contained in a form depends on the kind of information the form owner wishes to collect from users.

Attributes

The form element accepts the global attributes and the following:

  • acceptcharset: Charset attribute is used to tell the browser the character set or encoding to use in order to display the HTML document correctly. In a form, the accept-charset attribute is used to enlist all the character encodings that are to be used by the form which the server accepts. The default value is UNKNOWN, which tells the server that the form uses the same character set as the document containing the form. Apart from the reserved string “UNKNOWN”, which defaults to the value in <meta charset=“utf-8”>, other values could be “ISO-8859-1”, “WINDOWS-1252”, and “UTF-16”, etc.
  • novalidate: This is a Boolean attribute used in a form object to deactivate native form validation in HTML5. HTML5 has native validation for some input types such as email and URL. When a user’s input fails to conform to the requirement, this validation is automatically turned on, asking the user to correct the entry. When this attribute is used, this native validation is turned off.

Examples: see below

  • autocomplete: This attribute has on and off When it is on, it tells browser to automatically complete entries in the form; when it is off, then the user must directly complete entries manually.
  • action: This attribute is used to specify the URL or program that will process the form. A form submission to the server may be processed by a PHP In this case, the URL of the PHP file that will process the form should be specified as the value of the action attribute. In the example below, when the form is submitted, the script specified in the action attribute will process the information. However, the value specified here can be overridden by the formaction attribute.

Example: see below

  • method: This attribute is used to specify the method used by the browser to submit the collected form data. The value could be post or The value specified can be overridden by the formmethod attribute.

Examples

See the Pen Form Element by KmacIMS (@kmacims) on CodePen.

What is the difference between the POST and GET method?

When sending form data, we can use either the POST or GET form methods within the opening tag of the form element. But our choice will depend on the size and nature of the data we are transmitting. The GET method can take about 3000 characters, and the form data is encoded within the URL of the browser using the name/value pair. This method should be used to query strings and when dealing with non-sensitive data. When this method is used, it will add the name/value pair to the URL in the action attribute separated by the ?.

A typical example of using the GET method is as follow:

<!--Example of the GET method-->

      <form method="GET" action="formeg.html">

      <input type="email" name="email" placeholder="enter email">

      <input type="url" name="url" placeholder="enter web address">

      <input type="submit" name="submit" formnovalidate="" value="Submit">

      </form>


The Result is as follow:

///formeg.html?email=come&url=waith&submit=Submit

In the POST method, form data is encrypted and submitted within a message body. Data submitted using the POST method is more secure compared to the GET method. Also, there is no size limitation when this method is used.

  • Enctype: This attribute is used only when the value of the method attribute is POST. It is used to specify the encryption type used to submit the form when a post method is used. It has the following values:
    • text/plain,
    • multipart/form-data, and
    • application/ x-www-form-urlencoded – This is the default attribute if encytpe attribute is not specified.

This attribute can be overridden by the formenctype attribute.

  • name: This is used to specify the name of the form.
  • Target: This attribute is used to indicate where to show a response after form submission. The default value is ­ Other values include _parent, _blank, and _top. This attribute can be superseded by the formtarget attribute.

Example

See form with PHP script above.

Form Controls

The Fieldset Element <fieldset>

This element is used to group form controls together. It works with the <legend> element. The <legend> element is used to specify a name for the group of controls within a given form.

Attributes

It takes on the global attribute as well as the following:

  • name: Specify the name of the fieldset.
  • form: This attribute is used to specify the form which an element belongs to. The attribute usually takes the id of the <form> element which the specified element is part of.

E.g.

<form id= “myForm”>

   <fieldset form= “myForm”>

   </fieldset>

</form>

  • disabled: Used to disable the element.

Example

 

See the Pen Fieldset and Legend by KmacIMS (@kmacims) on CodePen.

The Legend Element <legend>

This element is usually used together with the fieldset element to provide a caption for a group of form input controls within the fieldset element.

Attributes

It takes on global attributes.

Example

Shown above

The Label Element <label>

This element is used to provide a caption or description of an item, especially, in a form.

Attributes

The element takes on the global attribute and the following specific attributes:

  • for: Used to create a relationship between the label and a form input element.
  • form: used to specify the form the label belongs to.

NOTE THAT WHENEVER THE FOR ATTRIBUTE IS USED IN A LABEL, THERE SHOULD BE A CORRESPONDING ID ATTRIBUTE IN THE FORM INPUT CONTROL, FOR IT TO HAVE EFFECT. WHEN A FORM INPUT CONTROL HAS A LABEL WITH A FOR ATTRIBUTE, CLICKING ON THE LABEL BRINGS THE INPUT TO FOCUS.

ALSO, DO NOT PLACE INTERACTIVE ELEMENTS SUCH AS BUTTONS, ANCHORS, INSIDE THE LABEL. DO NOT USE THE HEADING ELEMENTS (H1 – H6) INSIDE THE LABEL ELEMENT.

Example

<form>

  <label for=”time”>Choose Start Time: </label>

  <input id=”time” type=”time” name=”time” step=”5″>

  <input type=”Submit” name=”Submit” value=”Update”>

</form>

The Option Element <option>

This element is used to define the contents or items within the <select> element, <datalist> element and <optgroup> element. It is used in these cases to create a dropdown menu item.

Attributes

Use global attributes and:

  • label: Used to define the meaning of the option.
  • disabled
  • selected: Used to specify an initial selection among available options. i.e. default selected option.
  • value: Used to specify the value to be submitted if the option is selected. If it is omitted, the text content of the option will be submitted.

Example

See below.

The Select Element <select>

This element is used to create a droplist in a form object. The <select> element is used alongside the <option> element to create the dropdown list from where a user can select from.

Attributes

Use global attributes and the following:

  • autocomplete,
  • autofocus: A Boolean attribute that specifies that the element should get focus as soon as the page loads.
  • disabled,
  • form,
  • multiple: This attribute allows users to select multiple options at the same time.
  • name:
  • required: This attribute is used to indicate that users must select an item before a form is submitted.
  • size: Used to define the number of options to be seen at once from the options. The default value is 0.

Example

see below

The Option Group Element <optgroup>

This element is used together with the <select> element to create an option grouping for a select element. It helps to group options together within a select element.

Attributes

Use the global attributes, and

  • disabled and
  • label: Used to specify a name for a group of options within the browser.

Example

see below

The Form Datalist Element <datalist>

This element is used to provide a list of predefined options or suggestions for an input element. It is usually used together with the <option> element to provide values for the suggestions such that when a user begins to type an item, the suggestions will appear for the user to choose from.

What is the difference between the <select> element and the <datalist> element?

The <select> element is used to create a dropdown list of items from where a user must select from. This element must provide at least one option from where a user can select from. The <datalist> attribute is used to specify a predefined list of dropdown items that provide suggestions for the user to select from. When used, the list attribute of the input element must be the same with the id attribute of the datalist element.

Attributes

It uses the global attributes.

Example

 

See the Pen Select, Optgroup and Datalist by KmacIMS (@kmacims) on CodePen.

The Output Element <output>

This element is used to accept and display the result of a calculation, or an outcome of a computation. This element only displays the result to users but does not allow them to manipulate such results. However, the result so displayed should come from values entered in the form object.

When will you use the output element?

You can use the output element when you want to display a result to users, and when such a result is derived from the values entered in the form object. In this case, the output element may be part of a shopping cart or a sales calculator. It makes sense to note that this element will need JavaScript to produce the result of the calculation.

Attributes

Use global attributes and the following: for, form, name.

Example

See the Pen Output Element by KmacIMS (@kmacims) on CodePen.

The Textarea Element <textarea>

The <textarea> element is used to define a multi-text input area for users. It is usually used to collect information such as comment on blog posts, or message on contact form. The size of a textarea element is usually specified by the rows and cols attributes.

Attributes

Use global attributes and the following:

  • autofocus – gets focus when page loads
  • cols: Used to specify the visible width of a textarea. Its default value is 20. The value must be a positive integer.
  • rows: Used to specify the number of visible lines of text in a textarea.
  • autocomplete,
  • disabled,
  • form,
  • maxlength: Used to specify the maximum number of characters a user can enter. When absent, then users can enter an unlimited number of characters.
  • minlength: Used to specify the minimum number of characters a user must specify in order to submit the form.
  • name,
  • placeholder: Used to describe a hint of values expected to be entered by users.
  • readonly: Used to make a textarea readonly; meaning that a user cannot modify text already in the area. a user can click within but cannot edit text.
  • required,
  • spellcheck: Used to activate browser spelling check for the textarea.
  • wrap: Used to specify how a text is wrapped when submitted. Its values are:
    • hard,
    • soft.

Example

<label for=”comment”>Comment Below</label><br>

<textarea cols=”25″ rows=”4″ id=”comment” name= “comment”>

</textarea>

The Button Element <button>

The button element is used to create a clickable object within a document or a form. Adding the <button> element will display a default button on the document, however, the button can be styled using CSS.

Attributes

The button element takes on the global attributes along with the following specific attributes:

  • autofocus (a Boolean attribute, button should have input focus on page load);
  • disabled (a Boolean, create non-interactive button);
  • form,
  • formaction: Used to specify the URL or a program that will process form when it is submitted. If specified, it overrides the action
  • formenctype: Used to specify how form data should be encoded when being submitted. It overrides the enctype
  • formmethod: Used to specify the method to be used by the browser to send or submit form data.
  • formnovalidate: Used to specify that a form should not be validated when it is submitted.

What is the difference between the formnovalidate attribute and novalidate attribute?

The novalidate attribute has been explained above. The formnovalidate attribute is also a Boolean attribute used to turn off form validation upon submission. It overrides the novalidate attribute, and is usually used when data entered in a form is to be saved for later. If this attribute is specified, then form entries can be submitted without validation. In this case, the form may have two submit buttons; one to save the data (which should have the formnovalidate attribute) and another to submit completed data.

Examples:

  • formtarget: Used to specify where to display response after form has been submitted. Overrides the target attribute when specified.
  • name: Used to specify button’s name.
  • type: Used to specify the type of button. A button can be of three types, namely:
    • Submit – which is the default if type is not specified. It submits data to the server for processing.
    • Reset – which changes all form controls to their initial values.
    • Button – This button type has no default behavior. The behavior would be added using a script.
  • value: Used to define an initial value of the button that will be submitted with the form data.

Examples

See the Pen Button Element by KmacIMS (@kmacims) on CodePen.

The Form Input Element <input>

The form <input> element is used to create user interaction, and to collect information from users using the form object.

The value of the input type attribute determines how the form input element works. There are different input types namely: text, button, color, checkbox, date, datetime-local, file, email, password, hidden, month, image, number, radio, range, time, tel, reset, submit, week, URL, and search.

Attributes

The input element has the global attributes in addition to attributes common to all the input types. However, there are some attributes specific to different input types, which they handle in special ways. Some commonly used attributes for all <form> <input> types include:

  • form,
  • disabled,
  • autocomplete,
  • autofocus,
  • name,
  • list,
  • readonly,
  • required,
  • type,
  • value, and
  • tabindex,

Associating Text to Inputs

It is good practice to associate text with a given input to help users and screen readers understand the type of input and data to be collected by the form input.

There are basically two ways to do this, namely:

  • by using the placeholder attribute, and
  • by using the <label>

The placeholder attribute and label are used to inform the user of the kind of text that should be entered in the text input. But the placeholder attribute appears within the input box while the label appears outside the input box.

It is good practice to always use the label rather than the placeholder for some reasons. For example, the moment you start typing within the input box, the placeholder disappears, it may also not be possible to translate texts in a placeholder if a site uses translate, also, labels help screen readers to understand the input required to enter.

Examples:

 

See the Pen Placeholder and Label by KmacIMS (@kmacims) on CodePen.

Form User-Entry Input Types

These are form input types that permit users to manually enter user information using the form controls as specified by the owner. User information requested could be displayed in the <label> element or by using the placeholder attribute.

Email:

The email input type allows the user to enter an email address or a list of email addresses separated with a comma. A user can add multiple email addresses separated with a comma if the multiple attribute is specified. The good thing with this input type is that it can validate that the address is a properly formatted email address.

The email type has the following specific attributes:

  • multiple: Allows a user to add more than one email address, separated by a comma. This is a Boolean attribute.
  • placeholder,
  • maxlength: Specifies the maximum length of characters the input accepts and must be an integer including 0, but excluding negative integers.
  • minlength: Specifies the minimum length of characters the input will accept in order to validate field and must be a positive integer, including 0.
  • spellcheck,
  • size: Use this attribute to specify the width of the input. The value must be a positive integer.
  • readonly, and
  • pattern: This attribute is used to specify what the input content must match for it to be valid. It imposes content constraint to users such that if a user’s input content does not match the pattern specified, the input will not validate.

Example

 

  <form>
      <input type="email" placeholder="enter your email" required><br>
      <button type="submit">Submit</button>
      
  </form> 


How do I use the pattern Attribute?

To use the pattern attribute, we use a regular expression that matches with the JavaScript RegExp object type.

How do I create a Pattern using RegExp?

Creating a RegExp pattern is beyond the scope of this tutorial. However, we shall illustrate how you will use a regular expression to create simple patterns for your input types. Let us begin with an example.

Let us assume that you want your users to enter a code which has only 2 uppercase letters. Then you can indicate it thus:

 

See the Pen Pattern examples by KmacIMS (@kmacims) on CodePen.

When using the regular expression to create patter, take note of the following:

  1. [a-z] indicates that input will match characters of lowercase letters, a to z.
  2. [A-Z] indicates that input will match characters of uppercase letters, A to Z.
  3. [0-9] indicates that input will match numbers from 0 to 9. You can also use “\d”.
  4. The above (1 – 3) above can be written as [A-Za-z0-9], which means that input will match digits 0 – 9, lower and uppercase letters Aa – Zz.
  5. [^a-z] indicates that input will NOT MATCH any characters of lowercase letters a-z. Similarly, in [^A-Z0-9], it means that none of the character ranges in the square bracket will be matched.
  6. “beans|rice” indicates that input must be either beans or rice. This input value is case sensitive. Thus, to accommodate uppercase, you can write: [Bb]eans|[Rr]ice.
  7. [a-z]{x} is used to limit the number of lowercase characters that will be entered to x; where x is an integer. E.g. [a-z]{3}.
  8. [A-Z]{y,z} limits the number of uppercase characters that will be entered within the range of y through z. E.g. [A-Z]{2,5}
  9. [A-Za-z]{a,} places a lower bound to the number of characters entered. Here, characters entered should not be less than a, but its upper bound is limitless.
  10. ([A-Z]{x})([0-9]{y}) is used to join input patterns together. Hence, the input must contain x uppercase letters and y numbers.

Examples of the above patterns are illustrated below.

 

See the Pen All Pattern Examples by KmacIMS (@kmacims) on CodePen.

Hidden:

This input type is used to hide an input element from users. If we want to include an input of type that we do not want the user to edit or see, we simply use the type, ‘hidden’. Such inputs of type hidden are usually used for security reasons.

Example

<input type= “hidden” name= “secId” value= “S12201”>

Number:

This type of input is used to request a number input from users. It has inbuilt validation that automatically validates the input and ensures that a number is entered. It may have a default value. It works with the following attributes:

  • max: Maximum value
  • min: Minimum value
  • readonly,
  • step: Value incremental size. If 1, then it increases by 1, if 2, by 2, etc.

Example

see below

Password:

This input type is useful when requesting a password input from a user. It helps the user to enter a password securely and, in a way, another person will not be able to read it, by showing each character with “*” or “.” Depending on the browser. This input type has the following attributes:

  • placeholder,
  • maxlength,
  • minlength,
  • size,
  • readonly.

Example

see below

Search:

The input element of type search is used to allow users enter search queries to search for information on the website. It is similar to the text input type, but exhibit some differences. If a value attribute is included, it is displayed as the default search query in the search box.

This input type has the following attributes:

  • size,
  • placeholder,
  • maxlength,
  • minlength,
  • pattern,
  • spellcheck.

Example

See the Pen Number, Pwd and search example by KmacIMS (@kmacims) on CodePen.

Tel:

The tel input element type is used to request a telephone no. from a user. This input type is not automatically validated like the email input type. This is because telephone nos. vary around the world. However, you can provide a pattern for the telephone no to be entered. The input type has the following additional attributes:

  • size,
  • placeholder,
  • maxlength,
  • minlength,
  • pattern,

Example

see below

Text:

The text input element type is used to request a single line text entry from users, such as first name, username, etc. It has the following added attributes:

  • size,
  • placeholder,
  • maxlength,
  • minlength,
  • pattern,
  • spellcheck,

Example

see below

url:

The url input element type is used to collect website address from users. It has the following attributes: size, placeholder, maxlength, minlength, pattern, spellcheck, readonly.

Examples

 

See the Pen Tel, text and URL examples by KmacIMS (@kmacims) on CodePen.

Form Select Input Types

Button:

The input type button can be used in place of the <button> element. However, it does not have a default behavior of the <button> element.

Remember that the button element has Submit & Reset behaviors. If you should use this input type, then you must write a JavaScript that will tell the button what to do. Use the value attribute to add a label to the button when using the input type button. For example:

<input type="button" value="My First Input Button">

Checkbox:

This type of input is shown as a square box in a form. These boxes allow the user of a form to tick or select the given value(s) from the list of values specified by the boxes. The user may select one or more values. A checkbox has a Boolean attribute called checked which is used to check a box by default. 

Also, the value attribute is used to send the name/value pair to the server when the form is submitted. For example, in the code below, if the form is submitted, the name/value pair will be favourite=rice.

Example

 

See the Pen Checkbox by KmacIMS (@kmacims) on CodePen.

Color:

This input type is used by a user to select color by using the color picker or by entering a seven-character hex value of the format: #34aaff, where the first 2 values after # represents red (rr), the second 2 values represents green (gg), and the last 2 blue (bb). If a value is not set by default, the browser sets the value to black. For example:

<input type="color" value="#34aaff">

An example using JavaScript: We will create a blockquote and a color input such that a user can select a color using the color picker to change the color of the blockquote from its default color to the selected color.

First, create the html.

Second, create the JavaScript.

Example

See the Pen Color input by KmacIMS (@kmacims) on CodePen.

Image:

 The input of type image is used to create a fanciful image button. Instead of having the normal button element, the source image is used for the button. This type of input does not accept the value attribute. This type of input has the following attributes: height, width, alt, src, formtarget, formnovalidate, formaction, formmethod, formenctype.

Example

see below

File:

The file type input allows a user to upload a file (image, video, etc) from his/her local storage on his/her computer to a server. A file may be uploaded to a server or can be manipulated with a JavaScript. The file’s value is a string that represents the path to the file on the user’s computer, e.g. “C:/users/images/image.jpg”.

The file input type has the following additional attributes:

  • accept – this attribute is used to specify the types of files to be accepted, e.g. jpg, .mov, pdf, etc. To specify any type of image, audio or video, use the following: image/*, audio/*, and video/* respectively;
  • multiple – this attribute allows a user to choose more than one file at once by holding the shift/ctrl key;
  • capture – this attribute is used to specify the source to be used to capture the file, especially for capturing an image or video. When this attribute is used, it is important that we specify the accept and value The accept attribute can be .jpg, .ogg, etc, while the value attribute can be user or environment. If it is user, then the user facing the camera will be used, else, the browser will default to its value.
  • files – this attribute is used to list the chosen files. It is a Filelist object specifying all the files selected, especially, when multiple attribute is used.

Examples

 

See the Pen Image and File by KmacIMS (@kmacims) on CodePen.

Radio:

This type of input is used to provide radio buttons on a form so that the user can select only one from the group. Each button will always have a value and a name. The value usually corresponds to the radio when selected, while the name is the same throughout the group. Radio buttons have the attribute, checked.

Example

see below

Range:

The range input type is used to specify a range of values a user must select from. This range of values does not appear in the form number input but in a slider form. This type of input may be used in audio controls (volume and balance). The range type of input has the following attributes max, min, step.

Example

see below

Reset:

The input element of type reset functions like a button element of type reset. The input type renders like a button and has a reset characteristic. When it is clicked, it resets all form input values to its default. The value of the input element of rest type is displayed on the button. However, if you omit the value attribute, it defaults to Reset depending on the browser.

Example

see below

Submit:

This input element type is used to submit a form to the server. If it has a value, the value string become the text represented on the button. But by default, if the value is not specified, the button’s text is submit depending on the browser. It has the following additional attributes: formnovalidate, formaction, formmethod, formenctype, formtarget.

Examples

 

See the Pen Radio, range, reset by KmacIMS (@kmacims) on CodePen.

Form DateTime Input types

Date:

This type of input is used to create a user interaction which allows the user to type in a date in the textbox or select a date using the date picker. The date type populates the box with year, month and day values, but does not include the time value. The date picker interface varies from browser to browser. The date type input accepts the following additional attributes: max, min, step and readonly.

Example

see below

Datetime-local:

This type of input is similar to the date input type, but it adds the time value in hours and minutes, using the user’s local time in PM or AM.

Example:

see below

Month:

The month input type is used to allow users to select month and year in the form YYYY-MM. The month input type has the following attributes: max, min, step, and readonly.

Example

see below

Time:

The time input type is used to collect information on time from users in the format: hours, minutes and seconds. Safari and internet explorer do not support this input type. We can include the step attribute to include the seconds’ value in the displayed time inputs. It has the following attributes: max, min, step, readonly.

Example

see below

Week:

The week input type is used to collect weekly data from users. It displays the yeas and the week from 1 – 52 weeks of the year. The internet explorer, mozilla and safari does not support this input type. It has the following attributes: min, max, readonly, step.

Examples

 

See the Pen Date, time month and week by KmacIMS (@kmacims) on CodePen.

Conclusion

Creating HTML forms is tasking, especially, when you want to create captivating forms for your users. This is why we took time to illustrate how to achieve it using important form controls.

Haven learnt how to build forms; you can build forms now without limit. What is remaining is how to style our form and other HTML elements, but we will get to that in another course. Before that, we still have one more topic to cover: TABLES. We will cover that in our last module. See you next week as we conclude with HTML Basics.