HTML - Forms



What is an HTML Form?

HTML Form is a way of collecting and submitting information of the site visitors. It helps in making our web page more interactive and user friendly. We can see its application in various areas, including registration forms, customer feedback forms, online survey forms and many more. In this tutorial, we will learn how to create a HTML form and how it works internally to send requests and retrieve responses.

How Does an HTML Form Work?

Consider a scenario where we incorporate a Form section into our HTML webpage. Whenever the browser loads that page and encounters the <form> element, it will generate controls on the page allowing users to enter the required information according to the type of control. There are various form controls available like text fields, textarea fields, drop-down menus, radio buttons, checkboxes and so on. We will explore them in more detail in upcoming chapters.

When users submit the form by clicking the button, the browser creates a package and forwards it to the server. Next, the server will perform the required processing and sends back a response to the browser in the form of a HTML web page.

Creating an HTML Form

The HTML <form> tag is used to create an HTML form and it has the following syntax −

Syntax

<form action = "Script URL" method = "GET|POST">
   form controls like input, textarea etc.
</form>

The <form> element contains various predefined tags and elements termed as form controls.

Example

In the following example, we will create a sample HTML form where a user can enter his/her name with the help of <form> element and form controls like input, type and name.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title> Sample HTML Form </title>
</head>
<body>
   <!-- Start of the form element -->
   <form action = " ">
      <!-- various form controls -->
      First name: <input type = "text" name = "first_name" />
      <br><br>
      Last name: <input type = "text" name = "last_name" />
      <br><br>
      <input type = "submit">
   </form>
</body>
</html>

Example

In the previous example, we designed a form that accepts user input but doesn't process the data. In this example, however, when users enter their name and click the Submit button, they will be redirected to Tutorialspoint's HTML Tutorial. The redirection only occurs if a name is provided, if not, the form will prompt the user to enter their name.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <title> Sample HTML Form </title>
</head>
<body>
   <!-- Start of the form element -->
   <form action = "https://www.tutorialspoint.com/html/index.htm" target="_blank" method = "post">
      <!-- various form controls -->
      First name: <input type = "text" name = "first_name" required/>
      <br><br>
      Last name: <input type = "text" name = "last_name" required/>
      <br><br>
      <input type = "submit">
   </form>
</body>
</html>
Advertisements