HTML Forms


HTML Forms are used to collect different kinds of user inputs like Name, Email, Contact Number, phone numbers & other details like payment details etc.


HTML <form> Element


The HTML <form> element is used to create an HTML Form. Here's the syntax:


<form>
  //All form components go here
</form>



The <form> tag acts as a container for holding different input elements like text fields, checkboxes, radio buttons, submit buttons etc.

The following sections will describe the different types of controls that we can use.


The <input> Element


This is the most commonly used form element. It accepts a type attribute, which allows us to display various types of user input fields. Let's have a look at some of them:


Type Syntax Description
text<input type="text">Displaying single line input field
number<input type="number">Displaying single line input number field
button<input type="button">Displaying a clickable button
submit<input type="submit">Displaying a submit button for submitting forms
radio<input type="radio">Displaying a radio button (for selecting one choice amongst many choices)
checkbox<input type="checkbox">Displaying a checkbox button (for either having no choice or having multiple choices)

In the following example, we have two input fields, and two labels.


<form>
<label>Name</label><br>
<input type="text" name="name">
<br>
<label>Email</label><br>
<input type="text" name="email">
</form>

Live Demo!


Output:





The <label> Element


The <label> works as a label for the input elements. It provides details regarding the input fields. Here's the syntax:


<label for="Email">Email</label>

Live Demo!


Submit & Reset Buttons


A submit button is used to send the form data to the server. <form> accepts an action attribute, so whenever a form is submitted using the submit button, the data is sent to the file specified in form's action attribute.

A reset button resets all the values in a form to their default values. If there's no value specified initally, then the input fields get empty.


Let's have a look at an example:


<form action="handle_form_data.php" method="post">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name">
  <input type="submit" value="Submit">
  <input type="reset" value="Reset">
</form>

Live Demo!


Output:


<input> name Attribute


While handling data from forms, name is an important attribute. If this attribute is removed, no data will be received through the form submission.


Let's check an example:


<form action="handle-data.php" method="post">
  <label for="name">Name:</label>
  <input required type="text" name="name" id="name">
  <input type="submit" value="Submit">
  <input type="reset" value="Reset">
</form>

Live Demo!

Using this name attribute, data will be retrieved in the next page!