The <input> element in HTML uses both the name and id attributes, but they serve different purposes.
1. name Attribute
The name attribute is used to specify the key that will be sent when the form is submitted. It’s how the data from the input is labelled for processing by the server. Without it, the input value will not be included in the form data.
2. id Attribute
The id attribute is used to uniquely identify an element in the HTML document. It allows CSS or JavaScript to target this specific input.
The id must be unique across the page, meaning no two elements can share the same id.
If you associate an <input> with a <label>, the for attribute of the <label> matches the id of the <input>, making it easier for users to click on the label to focus on the input.
id-vs-name.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Form</title> </head> <body> <h2>Registration Form</h2> <form action="https://httpbin.org/post" method="POST"> <label for="username">Username:</label><br> <input type="text" id="username" name="myUsername" required><br><br> <label for="email">Email:</label><br> <input type="email" id="email" name="myEmail" required><br><br> <label for="password">Password:</label><br> <input type="password" id="password" name="myPassword" required><br><br> <button type="submit">Register</button> </form> </body> </html>
Upon submitting the form, you will be redirected to below screen. You can validate that myEmail, myPassword and myUsername are visible there.
Previous Next Home
No comments:
Post a Comment