Password Input Toggle in Alpine.js

July 07, 2021

Tags: Alpinejs, Javascript

In our client work, we typically eschew "password confirmation" fields. These days confirmation fields serve little purpose and are mostly just an annoyance to the user. With easy password reset flows, it's trivial for a user to self-service reset their password.

However, when working with passwords as a user, it is nice to see what you've typed when you run into errors. By default password fields obfuscate the value of what you type for security, but with some JavaScript we can easily change the password input to a text input so the user can verify what they've typed.

Here's what we're aiming for:

Password Input

Initially it's a password field and the button to the right says "SHOW". When you click the button, it changes the password field to plain text. The button text also changes to say "HIDE".

To do this, we're going to use Alpine.js, since it integrates easily with Phoenix LiveView. The code is also quite trivial.

<label class="flex w-full body text-gray-600 required" for="password">Password</label>
<div class="relative" x-data="{ input: 'password' }">
  <input class="flex w-full text-body-l h-12 rounded-md px-2 py-3 text-gray-800 border border-solid border-gray-300" id="password" name="user[password]" type="password" x-bind:type="input">
  <div class="absolute right-0 top-0 mr-2 mt-3" x-on:click="input = (input === 'password') ? 'text' : 'password'">
    <span class="body text-show-hide text-gray-600 uppercase cursor-pointer" x-text="input == 'password' ? 'show' : 'hide'">show</span>
  </div>
</div>

First we mount an Alpine component using x-data. We save the current input in the component so we can easily toggle it; we default it to password.

We use x-bind:type on the input, which tells Alpine to update the input's type attribute based on the value of our component's input param.

We use x-on:click on the SHOW/HIDE button and do a simple test to see if we should set input to text or password based on the current value; essentially all we want to do is toggle to the alternate value. (Remember that this element can't be a button; by default buttons inside forms have click handlers that submit the enclosing form.) We also use x-text here to update the button's label to SHOW or HIDE, again toggling between the values.

And that's it! See this CodePen for a working example.

Logan Leger

Founder & CEO

Founder. Engineer and entrepreneur. Husband and father. Writes in Ruby, Elixir, JavaScript, and Swift. he/him

let's talk.

Together we can make something great.

contact us about new work

Contact

225-407-4520

hello@newaperio.com

Social Media