As a web developer, I often come across the need to create login functionality for websites. One common requirement is to make the login button redirect to a specific sub page after successful authentication. In this article, I will guide you through the process of achieving this functionality.
Step 1: HTML Structure
First, let’s start by creating the HTML structure for our login form. We’ll need an input field for the username, an input field for the password, and of course, the login button.
<form>
<input type="text" id="username" name="username" placeholder="Username">
<input type="password" id="password" name="password" placeholder="Password">
<button id="login-btn">Login</button>
</form>
Step 2: Adding JavaScript
Next, we need to add some JavaScript code to handle the login functionality and the redirection. We’ll use the addEventListener()
function to listen for the click event on the login button. Inside the event listener, we’ll check if the username and password are correct, and if so, redirect the user to the desired sub page.
document.getElementById('login-btn').addEventListener('click', function() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// Check if username and password are correct
if (username === 'myusername' && password === 'mypassword') {
// Redirect to the sub page
window.location.href = 'https://www.example.com/subpage';
} else {
alert('Invalid username or password');
}
});
Step 3: Testing and Personalization
Now that we have our code in place, let’s test it out! Enter your username and password in the respective fields and click the login button. If your credentials are correct, you should be redirected to the sub page.
Remember to personalize this code to fit your specific needs. You can change the input field IDs, the username and password values, and the redirection URL to match your application’s requirements.
Conclusion:
Implementing a login button that redirects to a sub page after successful authentication is a common requirement in web development. By following the steps outlined in this article, you can easily achieve this functionality in your own projects. Remember to test and personalize the code to fit your specific needs.