Tips for modifying the class of a span inline element using a javascript function

Looking for assistance in creating a password text box with an eye icon that toggles visibility. When the user clicks on the eye icon, it should change to a crossed-out eye icon and switch the input type to text.

<div class="input-group show-hide-password">
      <form:password id="form-control" path="password" class="form-control" required="" />
       <div class="input-group-append">
         <span id="PassSpan" class="input-group-text" onclick="typeChange('form- 
         control','PassSpan')">
          <i class="fa fa-eye"  aria-hidden="true"></i> 
         </span>
       </div>
</div>

Javascript function:

function typeChange(controlId, spanId) { 
     var x =  document.getElementById(controlId);        
     if (x.type === "password")
     { x.type = "text";         
     } 
     else { 
         x.type = "password";           
         } 
 }

I have successfully implemented the input type change functionality, but I am struggling to also change the class to 'fa fa-eye-slash' for the icon within the span element. The classes are defined in the CSS file, but I am unsure how to dynamically update the class of the HTML element.

If anyone has a solution for this, I would greatly appreciate your help.

Answer №1

You can find an example below that demonstrates the desired functionality. (taken from a codepen fiddle)

$(".toggle-password").click(function() {
  $(this).toggleClass("fa-eye fa-eye-slash");
  var input = $($(this).attr("toggle"));
  if (input.attr("type") == "password") {
    input.attr("type", "text");
  } else {
    input.attr("type", "password");
  }
});
.panel {
  margin: 20px;
}

.field-icon {
  float: right;
  margin-left: -25px;
  margin-top: -25px;
  margin-right: 10px;
  position: relative;
  z-index: 2;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="panel panel-default">
  <div class="panel-body">
    <form class="form-horizontal" method="" action="">
      <div class="form-group">
        <label class="col-md-4 control-label">Password</label>
        <div class="col-md-6">
          <input id="password-field" type="password" class="form-control" name="password" value="mypassword">
          <span toggle="#password-field" class="fa fa-fw fa-eye field-icon toggle-password"></span>
        </div>
      </div>
    </form>
  </div>
</div>

Answer №2

Thanks everyone! I was able to resolve the issue by creating a new JavaScript function and calling it onclick.

function togglePasswordVisibility(controlId, spanId) { 
     var inputField =  document.getElementById(controlId);
     if ( spanId.classList.contains('fa-eye') ){
         spanId.classList.toggle('fa-eye-slash');
     }
     if (inputField.type === "password")
     { inputField.type = "text";      
     }
     else { 
         inputField.type = "password"; 
     }
}

Here is the snippet of JSP code:

<i class="fa fa-eye" id ="passi" aria-hidden="true" onclick="togglePasswordVisibility('form-control',this)"></i>

Answer №3

Feel free to test out this code snippet which is designed to modify the CSS classes of your HTML tags.

function hasClass(el, className)
{
    if (el.classList)
        return el.classList.contains(className);
    return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

function addClass(el, className)
{
    if (el.classList)
        el.classList.add(className)
    else if (!hasClass(el, className))
        el.className += " " + className;
}

function removeClass(el, className)
{
    if (el.classList)
        el.classList.remove(className)
    else if (hasClass(el, className))
    {
        var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
        el.className = el.className.replace(reg, ' ');
    }
}
function typeChange(controlId, spanId) { 
console.info(spanId);
var x =  document.getElementById(controlId);
var iconObj = document.getElementById(spanId);
if (x.type === "password"){
x.type = "text";
for(var i = 0; i < iconObj.children.length; i++){
if(iconObj.children[i]!=null && hasClass(iconObj.children[i], "fa-eye")){
removeClass(iconObj.children[i], "fa-eye");
addClass(iconObj.children[i], "fa-eye-slash");
}
}
} else {
x.type = "password";
for(var i = 0; i < iconObj.children.length; i++){
if(iconObj.children[i]!=null && hasClass(iconObj.children[i], "fa-eye-slash")){
removeClass(iconObj.children[i], "fa-eye-slash");
addClass(iconObj.children[i], "fa-eye");
}
}
} 
}

<div class="input-group show-hide-password">
      <form:password id="form-control" path="password" class="form-control" required="" />
       <div class="input-group-append">
         <span id="PassSpan" class="input-group-text" onclick="typeChange('form- 
         control','PassSpan')">
          <i class="fa fa-eye"  aria-hidden="true"></i> 
         </span>
       </div>
</div>

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

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

The submission feature for the textarea in Javascript is not functioning properly

As someone who is new to frontend development, I am currently facing a challenge with debugging JavaScript code that involves making changes to the content of a textarea. Despite my efforts to debug using the browser console, I have yet to identify why it ...

Is there any trouble with this controller method?

Every time I use routers without controllers, they work perfectly fine. But the moment I add controllers to them, my routers stop working completely. Can someone please shed some light on what might be causing this issue with my router functions? LOGIN CO ...

What is causing the issue with dynamic special characters not functioning properly in my React router?

I am working with 3 components named App.js, SearchCategoryPage.js, and Home.js. However, when I click on the search icon, it does not navigate me to the search page. What could be the reason for this issue? App.js const outlet_id = useSelector((state) =& ...

"Implementing classes with AngularJS: A Step-by-Step Guide

Is there a way to dynamically add a class to the i tag after a button is clicked in AngularJS? <button type="button" title="Like" ng-click="countLikes(product.title)" class="btn btn-compare"> <i class="fa fa-thumbs-o-up"></i> </ ...

Is it possible to center an anchor link in React JS using Webpack, Sass, and Bootstrap 4?

Recently, I started delving into React JS and Webpack but encountered a perplexing issue. My goal is simple - to center an anchor link on the screen. However, despite trying various methods like inspecting the element, removing inherited styles, setting wi ...

What are the steps to connect to multiple databases with ExpressJS?

I have a server with 3 databases containing identical tables. The databases are named DB1, DB2, and DB3. When working with a specific database, I utilize the following code in app.js: var cnxDB = require('./routes/cnxDB'); app.post('/user ...

How to implement setState within a Promise function using useEffect in React functional components with hooks?

I am struggling to set the value of a hook within a Promise function inside a useEffect(), and then store the returned promise value in the fruit hook so that it can be accessed in the return function of MyComponent() This is what I have attempted so far: ...

Aligning content within a div block

I created a div block that houses a form structured like this: <div class="divClass"> <form id="frm" method="post" action="/NotDefinedYet/index.xhtml" class="frmClass"> <input type="text" name="j_idt9:j_idt10:Username" placehold ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Trigger javascript function with a button click

Is there a way to trigger a JavaScript function from an HTML button that is not functioning properly? REVISED To see the issue in action, please visit this jsfiddle link: http://jsfiddle.net/winresh24/Sq7hg/341/ <button onclick="myFunction()">Try i ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

What are the solutions for resolving the TypeError when undefined is not an object error?

I'm currently working on a project where I need to fetch data from a JSON file using XMLHttpRequest and then store it in an array. However, I keep getting errors when attempting to do so. Take a look at this code snippet that seems to be causing the ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

The activity.from object in the messageReaction is lacking the name property

During my testing of an MS Teams bot, I have incorporated the onReactionsAdded event as shown below. this.onReactionsAdded(async (context, next) => { var name=context.activity.from.name; . . . } However, it seems that the name property ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Can we leverage map/filter/reduce functions within a promise by encapsulating the result with Promise.resolve()?

Currently, my approach to doing loops inside a promise looks like this: asyncFunc() .then(() => { return new Promise((resolve) => { for (let i = 0; i < length; i++) { // do something if (j == length - 1) { ...

Modify a number with a check box using inline Ajax

I have an HTML structure similar to this example: <li><label class="desc"><font color="green">Want to receive emails ($<span id="price">50</span>/month)</font></label> <input type="checkbox" checked ...

"Implementing automated default values for Select/dropdown lists in ReactJs, with the added capability to manually revert back to the default selection

After browsing multiple websites, I couldn't find a clear solution on how to both set and select a default value in a select element. Most resources only explain how to set the value, without addressing how to reselect the default value. My Requireme ...