What is Name Attribute in Form in HTML: Simple Explanation
name attribute in an HTML form element assigns a unique identifier to each input field. It is used to label the data when the form is sent to a server, so the server knows which value belongs to which field.How It Works
Think of a form like a questionnaire you fill out on paper. Each question needs a label so the person reading your answers knows what each answer means. In HTML forms, the name attribute acts like that label for each input box.
When you submit a form, the browser sends the data as pairs of name and value. For example, if you have an input with name="email" and you type your email address, the browser sends "email" along with your typed value. This helps the server understand what each piece of data is.
Without the name attribute, the form data won't be properly identified or sent, much like answering questions without labeling them.
Example
This example shows a simple form with two input fields, each having a name attribute. When submitted, the browser sends the names and values together.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form Name Attribute Example</title> </head> <body> <form action="/submit" method="POST"> <label for="username">Username:</label> <input type="text" id="username" name="username" placeholder="Enter username" required> <br><br> <label for="email">Email:</label> <input type="email" id="email" name="email" placeholder="Enter email" required> <br><br> <button type="submit">Submit</button> </form> </body> </html>
When to Use
Use the name attribute on every input, select, and textarea inside a form when you want to send data to a server. It is essential for forms that collect user information like login details, contact forms, surveys, or any data submission.
Without name, the form data for that field will not be included in the submission, so the server won't receive it. This makes name critical for processing user input correctly.
Key Points
- The
nameattribute labels form fields for data submission. - It connects the input value to a key sent to the server.
- Every input that should send data needs a unique
name. - Without
name, the input's data is ignored on submit.