Friday, 10 January 2025

Understanding the HTML form Element: Attributes, Examples, and JavaScript Integration

The <form> element in HTML is used to create an interactive form for users to input data and submit it to a server. Forms are essential for tasks like user registration, login, feedback, and more.


Key Attributes of <form> Element

1.   action: This attribute specifies where the form data should be sent when the form is submitted. The value of the action attribute is typically a URL that points to a server-side script (like a PHP, Python, or JavaScript file) that processes the form data.

 

·      Example

action="/submit-form" means the form data will be sent to the /submit-form URL for processing.

 

2.   method: This attribute specifies how the form data will be sent to the server. There are two common methods:

 

·      GET: Sends the form data appended to the URL as a query string. This is suitable for simple form submissions where the data can be seen in the URL.

 

·      POST: Sends the form data in the body of the request, making it more secure and suitable for sending sensitive data (like passwords).

 

·      Example:

method="POST" means the form data will be sent as a part of the HTTP request body, not in the URL.

 

registration.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="/submit-registration" method="POST">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" required><br><br>
        
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>
        
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" required><br><br>
        
        <button type="submit">Register</button>
    </form>
</body>
</html>

Above snippet generate below screen.


 

The form asks for a username, email, and password. When the user submits the form by clicking the "Register" button, the data will be sent to /submit-registration using the POST method. This ensures that sensitive data, like the password, is not exposed in the URL.


Previous                                                    Next                                                    Home

No comments:

Post a Comment