JavaScript Objects And Form Handling | Lecture 36 - BLOG PK
Skip to content

JavaScript Objects And Form Handling | Lecture 36

JavaScript Objects And Form Handling

Let’s begin with Lecture 36 of the HTML5 & CSS3 series. JavaScript Objects & Form Handling – Storing Data and Managing Input. This lecture is for absolute beginners; even kids can follow along and understand.

🎯 Objective:

By the end of this lecture, you will:

  • Understand what JavaScript objects are and how to use them
  • Be able to store complex data like user profiles or product info
  • Know how to handle form submissions using JavaScript
  • Build a login form or contact form that stores user input
  • Make your website smarter by combining forms with objects!

πŸ“¦ What Are JavaScript Objects?

Objects are like labeled boxes β€” they let you store multiple values in one variable, each with its own name (called a key ).

Think of it like this:

If arrays are backpacks for items in order, then objects are labeled drawers β€” each drawer has a name and holds something different.

Example:
let user = {
    name: "Naji",
    age: 12,
    email: "naji@example.com",
    isStudent: true
};

You can access properties like this:

console.log(user.name); // Naji
console.log(user.email); // naji@example.com
🧠 Why Use Objects?
BENEFITDESCRIPTION
Organized DataStore related info together
Easy AccessGet any value using dot notation (user.name)
Reusable StructureCreate many users with same format
Form HandlingStore and process user input easily
πŸ’» Try This: Store User Info Using an Object

Let’s build a simple app that takes user input and stores it in an object.

Step 1: Create a New File

In your VS Code project folder (MyFirstWebsite), create a new file named:

user-profile.html
Step 2: Add This Code
<!DOCTYPE html>
<html>
<head>
    <title>User Profile</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 40px;
        }

        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
        }

        .profile {
            margin-top: 20px;
            padding: 15px;
            background-color: #f0f0f0;
            border-left: 4px solid #3498db;
        }
    </style>
</head>
<body>

    <h2>Create Your Profile</h2>
    <label>Name:</label><br>
    <input type="text" id="userName"><br><br>

    <label>Email:</label><br>
    <input type="email" id="userEmail"><br><br>

    <button class="btn" onclick="saveProfile()">Save Profile</button>

    <div id="output" class="profile"></div>

    <script>
        function saveProfile() {
            // Get values from inputs
            let name = document.getElementById("userName").value;
            let email = document.getElementById("userEmail").value;

            // Create object to store data
            let user = {
                name: name,
                email: email,
                dateAdded: new Date().toLocaleDateString()
            };

            // Display profile on page
            let output = document.getElementById("output");
            output.innerHTML = `
                <strong>Name:</strong> ${user.name}<br>
                <strong>Email:</strong> ${user.email}<br>
                <strong>Added:</strong> ${user.dateAdded}
            `;
        }
    </script>

</body>
</html>
Step 3: Run with Live Server

Right-click the code β†’ Show All Commands β†’ Launch Live Server

πŸŽ‰ You’ve built a simple profile creator β€” now users can enter their info and see it stored in a JavaScript object!

JavaScript Objects And Form Handling
JavaScript Objects And Form Handling
πŸ’‘ Bonus: Build a Simple Login Form with Validation

Let’s make a login system that checks if the user exists in our database.

Step 1: Define Some Users

Add this at the top of <script>:

let users = [
    { username: "naji", password: "pass123" },
    { username: "sadia", password: "hello456" }
];
Step 2: Add HTML for Login
<h2>Login</h2>
<label>Username:</label><br>
<input type="text" id="loginUser"><br><br>

<label>Password:</label><br>
<input type="password" id="loginPass"><br><br>

<button class="btn" onclick="login()">Login</button>
<p id="loginResult"></p>
Step 3: Add JavaScript Function
function login() {
    let username = document.getElementById("loginUser").value;
    let password = document.getElementById("loginPass").value;
    let result = document.getElementById("loginResult");

    // Check if user exists
    let found = false;

    for (let i = 0; i < users.length; i++) {
        if (users[i].username === username && users[i].password === password) {
            found = true;
            break;
        }
    }

    if (found) {
        result.textContent = "βœ… Login successful!";
        result.style.color = "green";
    } else {
        result.textContent = "❌ Invalid username or password.";
        result.style.color = "red";
    }
}

Now users can try logging in with predefined usernames and passwords! πŸ”

πŸ’‘ Bonus: Save Data to Console or Alert

You can also log the full user object:

result.textContent = JSON.stringify(user, null, 2);

Or show a friendly message:

alert("Welcome back, " + user.name + "!");

πŸ§ͺ Try It Yourself!

  1. Add a “Sign Up” section that pushes new users into the users array.
  2. Use localStorage to save user data even after refresh (we’ll cover this more later).
  3. Add a password strength meter that shows feedback as the user types.
  4. Style the success/error messages with green/red backgrounds using JavaScript.
βœ… Summary of What You Learned Today
CONCEPTCODE EXAMPLE
Object Syntaxlet user = { name: "Naji", age: 12 };
Access Propertyuser.name, user["email"]
Form Inputsdocument.getElementById("id").value
Display Outputelement.innerHTML = "..."
Check Conditionsif (user.password === enteredPassword)
Loop Through Arrayfor (let i = 0; i < users.length; i++)

πŸš€ Next Lecture Preview:

In Lecture 37 , we’ll learn how to work with localStorage and sessionStorage β€” so you can store data permanently or temporarily in the browser β€” perfect for saving user preferences, scores, or login info across sessions!

Stay Updated

If you found this information useful, don’t forget to bookmark this page and Share.

HTML5 and CSS3 Compleate Series

Najeeb Alam

Najeeb Alam

Technical writer specializes in developer, Blogging and Online Journalism. I have been working in this field for the last 20 years.