HTML Forms

HTML forms are used to collect user input, such as text, numbers, and choices, and submit it to a web server for processing. A form is made up of one or more form elements, such as input fields, select menus, and buttons. In this article, we'll cover the basic syntax of HTML forms, as well as some of the most common form attributes.

Basic Syntax of HTML Forms

To create an HTML form, you use the

element. The basic syntax of an HTML form looks like this:

1<form action="process-form.php" method="POST"> 2 <!-- form elements go here --> 3</form>

In this code, the action attribute specifies the URL of the script that will process the form data, and the method attribute specifies the HTTP method used to submit the form data. The two most common HTTP methods used for form submissions are POST and GET.

HTML Form Attributes

Here are some of the most commonly used attributes in HTML forms:

  • action: Specifies the URL of the script that will process the form data.

  • method: Specifies the HTTP method used to submit the form data, either GET or POST.

  • name: Assigns a name to the form, which can be used in JavaScript to manipulate the form.

  • enctype: Specifies the encoding type of the form data when it is submitted. The two most common encoding types are application/x-www-form-urlencoded and multipart/form-data.

  • autocomplete: Enables or disables form field autocompletion.

  • novalidate: Disables form validation, which can be useful during development.

  • target: Specifies where to display the response after the form is submitted. The two most common values are _self and _blank.

  • accept-charset: Specifies the character set used to encode the form data when it is submitted.

  • onsubmit: Specifies a JavaScript function to run when the form is submitted.

Example of HTML Forms:

Here's an example of a simple HTML form with two text input fields and a submit button:

1<form action="process-form.php" method="POST"> 2 <label for="name">Name:</label> 3 <input type="text" id="name" name="name"><br><br> 4 <label for="email">Email:</label> 5 <input type="email" id="email" name="email"><br><br> 6 <input type="submit" value="Submit"> 7</form>

In this code, we've added two text input fields and a submit button to the form. We've also included the for attribute on the <label> element to associate the label with the corresponding input field, and the id attribute on the input fields to make them unique and reference them in the label elements. When the user clicks the "Submit" button, the form data will be sent to the URL specified in the action attribute using the HTTP method specified in the method attribute.

When you open this web page in a browser, you will see a form with two input fields and a submit button. When you fill out the form and click the "Submit" button, the form data will be sent to the URL specified in the action attribute for processing.