Utilize a single function to toggle the visibility of passwords for multiple fields upon clicking

Is there a way to optimize the function used to hide passwords for multiple fields when clicked? Instead of having separate functions for each field, I would like to have one function that is only active on the clicked button. For example, if the toggle button is clicked for the current password field, it should only affect the current password field. The same goes for the new password and confirm new password fields.

 <form id="update-password-form" action="" method="post">
 <div class="updatepwd"&}gt;
 <div class="form-field">
   <label for="current-password">Current Password <span class="asterisk">*</span>
   </label>
   <input type="password" name="current-password" id="passwordField" required>
   <span class="toggle-btn" onclick="togglePasswordVisibility()">👁️</span>
 </div>
 <div class="form-field">
   <label for="new-password">New Password <span class="asterisk">*</span>
   </label>
   <input type="password" name="new-password" id="passwordField1" required>
   <span class="toggle-btn" onclick="togglePasswordVisibility1()">👁️</span>
 </div>
 <div class="form-field">
   <label for="confirm-password">Confirm New Password <span class="asterisk">*</span>
   </label>
   <input type="password" name="confirm-password" id="passwordField2" required>
   <span class="toggle-btn" onclick="togglePasswordVisibility2()">👁️</span>
 </div>
  </div>
  <input type="submit" name="submit" value="Submit">
  </form>
<script>
function togglePasswordVisibility() {
 var passwordField = document.getElementById('passwordField');
 var toggleBtn = document.querySelector('.toggle-btn');
 if (passwordField.type === 'password') {
   passwordField.type = 'text';
   toggleBtn.textContent = '👁️';
 } else {
   passwordField.type = 'password';
   toggleBtn.textContent = '👁️';
 }
 }

 function togglePasswordVisibility1() {
 var passwordField = document.getElementById('passwordField1');
 var toggleBtn = document.querySelector('.toggle-btn');
 if (passwordField.type === 'password') {
   passwordField.type = 'text';
   toggleBtn.textContent = '👁️';
 } else {
   passwordField.type = 'password';
   toggleBtn.textContent = '👁️';
 }
 }

 function togglePasswordVisibility2() {
 var passwordField = document.getElementById('passwordField2');
 var toggleBtn = document.querySelector('.toggle-btn');
 if (passwordField.type === 'password') {
   passwordField.type = 'text';
   toggleBtn.textContent = '👁️';
 } else {
   passwordField.type = 'password';
   toggleBtn.textContent = '👁️';
 }
 }
 </script>

Answer №1

To optimize your HTML code, it is recommended to eliminate onclick attributes from span elements and utilize the data-toggle-target data attribute to associate each toggle button with its respective password field.

document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.toggle-btn').forEach(button => {
        button.addEventListener('click', function () {
            var passwordFieldId = this.getAttribute('data-toggle-target');
            var passwordField = document.getElementById(passwordFieldId);
            if (passwordField.type === 'password') {
                passwordField.type = 'text';
                this.textContent = '👁';
            } else {
                passwordField.type = 'password';
                this.textContent = '👁️';
            }
        });
    });
});
<form id="update-password-form" action="" method="post">
    <div class="updatepwd">
        <div class="form-field">
            <label for="current-password">Current Password <span class="asterisk">*</span></label>
            <input type="password" name="current-password" id="passwordField" required>
            <span class="toggle-btn" data-toggle-target="passwordField">👁️</span>
        </div>
        <div class="form-field">
            <label for="new-password">New Password <span class="asterisk">*</span></label>
            <input type="password" name="new-password" id="passwordField1" required>
            <span class="toggle-btn" data-toggle-target="passwordField1">👁️</span>
        </div>
        <div class="form-field">
            <label for="confirm-password">Confirm New Password <span class="asterisk">*</span></label>
            <input type="password" name="confirm-password" id="passwordField2" required>
            <span class="toggle-btn" data-toggle-target="passwordField2">👁️</span>
        </div>
    </div>
    <input type="submit" name="submit" value="Submit">
</form>

Upon clicking a button, the provided function determines the appropriate password field to toggle based on the data-toggle-target attribute of the clicked button.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

Testing a Vue.js/Node.js application using Websockets

I'm working on a Vue project (version 3.0.3) integrated with a Node.js server. Can you provide guidance on how to conduct unit testing for this setup? The application is a game that relies on web-sockets for communication. ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Discover the method to calculate the combined file size of multiple uploads with jquery

One of the challenges I'm facing is ensuring that users can only upload multiple files if the total size does not exceed 3GB. Is there a way I can enforce this limit? Below is the current code snippet I am using: var fileCount = 0; var showFileCo ...

Clicking on the Angular Material Table will reveal the items for display

Only when I click on the table do items display. Upon initially loading the page, the table is empty for reasons unknown to me. I retrieve data from Rest-API Cloud Blobstorage and populate the empty Array with it. Check out the code snippet below: impor ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

I'm curious about the reason behind the error message stating "Navbar is defined but never used" popping up while working with Vue

After importing the Navbar component from Navbar.vue, I attempted to include it in my app.vue. However, upon doing so, I encountered an error stating 'Navbar' is defined but never used. As a newcomer to Vue, I am unsure of why this issue is occur ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Updating every occurrence of a string in the visible text of a webpage: A step-by-step guide

I need to include the registered trademark symbol beside all mentions of a brand, which I'll refer to as "SomeBrand", on a client's website. Here is my current approach: function updateSomeBrand(){ var elements = document.getElementsByTagName( ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

Having issues with the functionality of the Material UI checkbox component

Having issues with getting the basic checked/unchecked function to work in my react component using material UI checkbox components. Despite checking everything, it's still not functioning as expected. Can someone please assist? Here's the code s ...

Steps for implementing a single proxy in JavaScript AJAX with SOAP, mirroring the functionality of the WCF Test Client

I am working with a WCF web Service and a javascript client that connects to this service via AJAX using SOAP 1.2. My goal is to pass a parameter to instruct the AJAX SOAP call to use only one proxy, similar to how it is done in the WCF Test Client by unch ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Adjust slider value dynamically with jQuery

I am working on a UI slider that ranges from 0 million to 20000 million. My goal is to change the displayed value when it reaches 1000 to show '1 milliard', and at 20000 to show '20 milliard'. For instance, if the value is 1100 millio ...

Utilizing React for Conditional Rendering and Navigation Bar Implementation

When developing my applications in react-native, I am using the state and a switch statement in the main render function to determine which component should be displayed on the screen. While this is a react structure question, it has implications for my sp ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...

Having trouble with uploading images using Form.File in React?

I'm facing an issue with my React code for uploading an image. It doesn't seem to be working and I can't figure out why. Can someone please assist me? return ( <div> <FormContainer> <h1>Edit Product& ...

What is the best way to play a video from a certain time point in a React application?

How can I make my component automatically play from a specific time like 00:07:12,600 instead of starting from the beginning? import style from './Hero.module.css'; import Image from 'next/image'; import ReactPlayer from 'react-pla ...