Site icon Puneet Sharma – Freelance Web Developer

Generic Javascript code for hide-show input-password

Generic Javascript code for hide-show input-password

Generic Javascript code for hide-show input-password

See the Pen Input field – show hide password by Puneet Sharma (@webdevpuneet) on CodePen.

HTML

<div>
    <input id="password1" type="password" class="">
    <span class="toggle-password" data-togglepassword="#password1">eye</span>
</div>

<div>
    <input id="password2" type="password" class="">
    <span class="toggle-password" data-togglepassword="#password2">eye</span>
</div>

JavaScript

$(document).ready(function () {
    // Hide/Show password toggle functionality using jQuery
    $('.toggle-password').on('click', function () {
        const toggleId = $(this).data('togglepassword'); // Get the selector from data-togglepassword attribute
        const $input = $(toggleId); // Select the input element by its ID or selector
        
        if ($input.length) {
            // Toggle input type between 'password' and 'text'
            if ($input.attr('type') === 'password') {
                $input.attr('type', 'text');
                $(this).addClass('active'); // Add active class for styling
            } else {
                $input.attr('type', 'password');
                $(this).removeClass('active'); // Remove active class
            }
        } else {
            console.warn(`No input element found for selector: ${toggleId}`);
        }
    });
});
Exit mobile version