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

Get access to the file upload field using ajax

I'm encountering an issue with accessing the file upload field //HTML <input type='file' name='images' id="images" multiple> ////////////////// $('.bt-add-com').click(function(){ var formdata = new For ...

Show a message of 'no results found' when implementing a jQuery plugin for filtering items in a list

I recently implemented the 'Filtering Blocks' tutorial from CSS-Tricks to filter items by category on an events website I'm developing. While the filtering functionality works perfectly, I realized that there is no mechanism in place to sho ...

What was the reason for node js not functioning properly on identical paths?

When the search route is placed at the top, everything works fine. However, when it is placed at the end, the route that takes ID as a parameter keeps getting called repeatedly in Node. Why does this happen and how can it be resolved? router.get('/se ...

Using more than one submit button in an HTML form

I am attempting to include multiple buttons on a single form. I would like to perform different actions on the form depending on which submit button is clicked. <script type="text/javascript> $("#<portlet:namespace/>Form").submit(function( ...

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...

Is there a way to utilize redux to trigger the opening of my modal when a button is clicked?

I'm facing a challenge with opening my modal using redux when clicking <CheckoutButton/>. Despite my efforts, the modal keeps appearing every time I reload the browser. I've reviewed my code but can't pinpoint the issue. What am I doin ...

How can I use HTML and jQuery to send a button click event to a .py file using AJAX and cgi in web development?

I have encountered a challenge with posting data from button clicks on an HTML page to Python CGI for insertion into a PostgreSQL database. My script seems to be struggling with this task. Here is the structure of my HTML, ajax, and javascript: '&ap ...

Oops! An issue occurred at ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 where a module cannot be located. The module in question is 'http'

I have been troubleshooting an issue with Next.js The error I am encountering => error - ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 Module not found: Can't resolve 'http' Import trace for req ...

What are the steps for integrating connect-multiparty into route paths?

I am looking to incorporate connect-multiparty into my routes. Upon researching, I found the following example... var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); app.post('/upload', multipartMiddle ...

Tips for preventing the sidebar from extending beyond the footer

I am facing an issue with my sidebar that follows as I scroll. How can I make it stop following when it reaches the footer? Here's what I have attempted so far: $(function() { var floatPosition = parseInt($("#left_menu").css('top')); ...

jQuery not functioning properly when attempting to add values from two input boxes within multiple input fields

I am facing an issue with a form on my website that contains input fields as shown below. I am trying to add two input boxes to calculate the values of the third input box, but it is only working correctly for the first set and not for the rest. How can ...

Is it conceivable that Jquery is failing to load for an Ajax request?

I have been experiencing an issue with my jQuery code not working within Ajax requests. The jQuery plugin I am using is FancyBox which can be found at . When calling the FancyBox plugin directly, everything works perfectly and multiple links load the plugi ...

An action in redux-toolkit has detected the presence of a non-serializable value

When I download a file, I store it in the payload of the action in the store as a File type. This file will then undergo verification in the saga. const form = new FormData(); if (privateKey && privateKey instanceof Blob) { const blob = new Blo ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Navigate the user to various pages in a Node.js application based on login status

Looking for guidance on a login system within my application? I need to redirect users based on their roles. Below is the code for the login controller, along with node.js snippets and the login HTML page. Any help would be appreciated. Login.html - < ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

`Discover the latest version of Tailwind using JavaScript or PHP`

My setup includes Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30, and Tailwind https://i.sstatic.net/fVbJB.png I am looking to fetch the Tailwind version in JavaScript similar to how I can get the Vue version using: //app.js require('./bootstrap'); ...

Enhancing an array item with Vuex

Is there a way to change an object within an array using Vuex? I attempted the following approach, but it was unsuccessful: const state = { categories: [] }; // mutations: [mutationType.UPDATE_CATEGORY] (state, id, category) { const record = state. ...

Enhancing elements with fade-in effects upon hovering

Is there a way to incorporate a subtle fade in/fade out effect when hovering over items on this webpage: http://jsfiddle.net/7vKFN/ I'm curious about the best approach to achieve this using jQuery. var $container = $("#color-container"), ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...