Alpine.js: Password Show/Hide Form Field
1 min readOct 22, 2024
Show/Hide Password in Form Input Field with Alpine.js
create index.html with alpinejs, bootstrap and bootstrap icon.
reference: alpinejs, bootstrap and bootsrap icon
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alpine JS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head>
<body class="container py-3">
<div x-data="{ passwordShow: false }">
<form>
<div class="input-group">
<input class="form-control" type="password" id="exampleInputPassword1" name="password" placeholder="Enter Password" x-bind:type="passwordShow ? 'text' : 'password'">
<div class="input-group-append">
<div class="input-group-text" x-on:click="passwordShow = !passwordShow">
<span x-bind:class="passwordShow ? 'bi bi-eye' : 'bi bi-eye-slash'"></span>
</div>
</div>
</div>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://unpkg.com/alpinejs" defer></script>
</body>
</html>
- The
x-data
directive is used to define a data objectpasswordShow
that tracks the password's reveal state. - The
x-bind:type
directive dynamically updates thetype
attribute of the password input based on thepasswordShow
value. - The
x-on:click
directive listens for clicks on icon and toggles thepasswordShow
value. - The
x-class
directive updates the eye/eye-slash icon on thepasswordShow
value.