Home > database >  Reveal password when user click on icon in input field
Reveal password when user click on icon in input field

Time:07-30

I want to reveal password when user click on icon in input field

My code

HTML

<form data-ajax_reset_submit="1" autocomplete="off" data-use-ajax="1" method="post" >
//fields
// password
<input type="password" id="dhe_form_control_user_password" name="user_password" value=""  required=""  placeholder="Password">
<span ><i ></i></span>
//confirm password
<input data-field-name="cuser_password" autocomplete="off" type="password" id="dhe_form_control_cuser_password" name="cuser_password" value=""  required="" placeholder="Confirm Password">
<span ><i ></i></span>
</form>

jquery (I use Wordpress)

jQuery(document).ready(function(){
  
  $('.dhe-form-add-on').on('click', function(){
    alert('2');
     if($(".dhe-form-control-user_password").attr('type')==='password')
       {
        $(".dhe-form-control-user_password").attr('type','text');
     }else{
      $(".dhe-form-control-user_password").attr('type','password');
     }
 })
})

But it works only for the first input fields. And if I click on second icon ( ) I will reveal the first password but no second

CodePudding user response:

Use "$(this).prev()" for select previous element and get attribute "type" like this:

$(document).ready(function(){
  
  $('.dhe-form-add-on').click(function(){
     if($(this).prev('input').attr('type')==='password'){
        $(this).prev('input').attr('type','text');
     }else{
      $(this).prev('input').attr('type','password');
     }
 });
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>

<form data-ajax_reset_submit="1" autocomplete="off" data-use-ajax="1" method="post" >
<input type="password" id="dhe_form_control_user_password" name="user_password" value=""  required=""  placeholder="Password">
<span ><i ></i></span>
<input data-field-name="cuser_password" autocomplete="off" type="password" id="dhe_form_control_cuser_password" name="cuser_password" value=""  required="" placeholder="Confirm Password">
<span ><i ></i></span>
</form>

  • Related