Login Form
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 25 of 27.
Challenge
EasyCreate a Login Form that validates credentials.
We have a login form with username and password fields. The username is pre-filled as "admin". Your job is to validate the password when the login button is clicked.
Steps:
- In JavaScript:
- Create variables for the password input, login button, and message element
- Add a click event listener to the login button
- When the login button is clicked:
- Check if the password equals "admin123"
- If correct, show: "Logged in successfully!" and set the message class to "success"
- If incorrect, show: "Invalid password" and set the message class to "error"
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="login-container">
<h2>Login</h2>
<form id="loginForm">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" value="admin" readonly>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" placeholder="Enter password">
</div>
<button type="button" id="loginBtn">Login</button>
<p id="loginMsg"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>