Search code examples
ruby-on-railsdevise

Show password button in rails devise


In my rails am using devise for authentication, i want add a button near the password field on click of which user will be able to see what password they typed.

I tried using javascript for this, added a checkbox and given it an onclcick function in the function if user clciks on the button the password type gets changes to text and vice versa.

is something wrong here.

<div class="form-group">
        <div class="input-group" style="z-index: 0;">
            <span class="input-group-addon"><i class="fa fa-lock"></i></span>
            <%= f.password_field :password, class: 'form-control password', autocomplete: "current-password", placeholder: "Your Password" %>
            <input type="checkbox" class="eye_icon" onclick="myFunction()">Show Password
        </div>
    </div>




<script>
$(".eye_icon").on('click',myFunction() {
    if ($(".password").attr('type') === 'password') {
        $(".password").attr('type', 'text');
    } else {
        $(".password").attr('type', 'password');
    }
});
</script>

Solution

  • I think your JS is the issue, specifically using myFunction in here, it should just be function. I suspect if you look at the concole with your current JS you are getting an error Uncaught SyntaxError: missing ) after argument list which should go away after you make the change in my code below. Everything else looked good.

    $(".eye_icon").on('click',function() {
      if ($(".password").attr('type') === 'password') {
          $(".password").attr('type', 'text');
      } else {
          $(".password").attr('type', 'password');
      }
    });
    

    Also, the click function you added to the HTML needs to come out. Notice how that function is called myFunction but nowhere do you create a function called that. I am guessing JS is a little new. So change the HTML to match the line below and you should be good to go.

    <input type="checkbox" class="eye_icon">Show Password