Toggle the Visibility of your Password

I am currently working on implementing a TypeScript function in my webpage to enable the toggling of password visibility using an icon. The desired functionality is as follows: when a button (in this case, a clickable icon) is pressed, the icon should change and the input field's type property should switch to "text" to display the entered password. Pressing the button again should revert the icon to its default state and change the input type back to "password".

Here is the code I have written:

togglePasswordVisibility() {
    document.querySelector("#input2").setAttribute("type", "password");
    
    document.querySelector("#passwordIcon").setAttribute("name", "eye-off");
    
    if (document.querySelector('#passwordIcon').getAttribute('name') == 'eye-off') {
      
      document.querySelector('#passwordIcon').setAttribute("name", "eye");
    }
}

The issue I am facing is that this implementation only works once, but I need it to be able to toggle password visibility multiple times. Any assistance would be greatly appreciated!

Answer №1

For those utilizing the newest ionic v8, there is a built-in component ion-input-password-toggle that can be used to toggle text visibility inside an input field with just a button click, eliminating the need for JS implementation.

<ion-input type="password" label="Password" value="YourPassword">
  <ion-input-password-toggle slot="end"></ion-input-password-toggle>
</ion-input>

Answer №2

Here is a breakdown of your code:

  • First, it sets the type to password
  • Then, if the type is already password, it changes it to text

The issue lies in the fact that the second condition will always be true, leading to it working only once. To fix this, you can update the code as follows:

togglePasswordVisibility() {    
  if (document.querySelector('#passwordIcon').getAttribute('name') == 'eye-off') {
    document.querySelector("#input2").setAttribute("type", "text")
    document.querySelector('#passwordIcon').setAttribute("name", "eye-off");
  } else {
    document.querySelector("#input2").setAttribute("type", "password");
    document.querySelector("#passwordIcon").setAttribute("name", "eye");
  }
}

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

npm encountered an issue when attempting to install a package from a local directory: EISDIR: illegal operation on a directory, read

While attempting to add my compiled TypeScript output as a local package using npm, this error appears: $ npm install --save ../app/out npm ERR! eisdir EISDIR: illegal operation on a directory, read npm ERR! eisdir This is most likely not a problem wit ...

The form embedded within the <tr> element seems to be malfunctioning

Hey there, I'm facing a little issue with my form that is nested inside a table content. It seems to not be working properly. Let me share the code snippet below: <table> <form name='editpo' method=POST action='js_buat_po.php? ...

The 'setParent' property is undefined and cannot be read

In my Angular 6 project, I am utilizing a reactive form which includes a table in a child component: <div formArrayName="_server"> <table id="_server" class="table table-striped table-bordered"> <thead> <tr> ...

The ion-slide-box does not update after the active-slide has been changed using $index

I'm currently facing an issue with the controller that corresponds to this specific view. .controller('MenuCtrl', ['$rootScope','$scope','$state','$timeout','$ionicSlideBoxDelegate', functio ...

Investigating issues with console errors and variables within callback functions in Angular 2 unit tests using Jasmine

I need assistance in achieving full coverage for this simple function, but I am struggling to do so. name-list.service.ts import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable ...

The JSON representation is not appearing for the newly introduced nested components

Building a nested component within another component and implementing two-way binding for dynamically added field values using the JSON pipe in the view. However, encountering an issue where the newly added values are not reflected in the JSON view. If yo ...

An issue was encountered in the karma/config.tpl.ts file at line 13, column 18 - a TS1109 error indicating that an expression was expected. This

I'm encountering the following error after updating to Angular 9, so I haven't downgraded TypeScript. Could someone please assist me? I've tried numerous solutions without success. node_modules/karma/config.tpl.ts:66:16 - error TS1005: &apo ...

Updating Angular 2 components using BaobabWould you like to learn how to

Exploring Baobab as a potential solution for developing Flux applications with Angular 2 has piqued my interest, but I have yet to come across any examples. My primary query revolves around the process of 'subscribing' an Angular Component to Ba ...

Ionic 5 Error: Unable to access 'subscribe' property of undefined object

Working with IONIC 5 service: import { HttpClient } from '@angular/common/http'; . . . getPlaces(placeId: string) { return this.httpClient.get( `https://test.com/offered-place/${placeId}.json`) } . . . Encountering an issue when tryin ...

Steps to allow an ng-model to accept a variety of input values

Imagine having an input box structured like this <ion-input [(ngModel)]="Gender" type="text" placeholder="Gender Type"></ion-input> <ion-input [(ngModel)]="hairCat" type="text" placeholder="Hair Type"></ion-input> Now, let's ...

Mastering the Art of Concise Writing: Tips to

Is there a way to write more concisely, maybe even in a single line? this.xxx = smt.filter(item => item.Id === this.smtStatus.ONE); this.yyy = smt.filter(item => item.Id === this.smtStatus.TWO); this.zzz = smt.filter(item => item.Id == ...

The npm warning indicates that the file node_modules/.staging/typescript-8be04997/lib/zh-CN/diagnosticMessages.generated.json does not exist due to an ENOENT error

I am currently in the process of running npm install on a Linux machine where I do not have sudo access. Unfortunately, I have a machine-specific package.json and package-lock.json that cannot be changed. However, I encountered some errors during the insta ...

Developing a custom React component library using Webpack and Typescript, however encountering issues with Webpack consistently bundling React

I'm currently in the process of developing an external component library using Webpack and TypeScript. Although it compiles without any issues, I encounter an error when attempting to use the library: Invalid hook call. Hooks can only be called ins ...

Using Typescript to create a mapped type that allows for making all properties read-only, with the exception of

I encountered a problem where I didn't want to repeatedly rewrite multiple interfaces. My requirement is to have one interface with full writing capabilities, while also having a duplicate of that interface where all fields are set as read-only excep ...

What is included in the final Angular build package selection?

Is there a tool available to track packages included in the final build of an Angular project? For instance: I am using the package "@angular/compiler" as a dependency in my package.json, but it is not a dev dependency. According to the Angular ...

Tips for verifying the presence of an "@" symbol in an email address submitted through a form

I am currently working on a form that includes both login and registration elements. The Form I'm Working On <form method="POST" action="login.php"> <input type="text" name="mail" value="Please enter your email"/> <input type= ...

Retrieve a specific number from an equation

With my limited knowledge of TypeScript, I am attempting to extract a specific number from an expression. The goal is to locate and retrieve the digit from the following expression. ID:jv.link.weight:234231 In the given string, I aim to extract the numb ...

Angular 13 throws NG0301 error message, failing to display the problematic module

Can someone provide assistance? Recently, I upgraded my Angular project from version 11 to version 13: Angular: 13.2.4 ... animations, cdk, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package ...

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...