0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryでパスワードを見えるようにする

Last updated at Posted at 2019-11-01

Railsでパスワードの入力フォームを使っているときに、パスワードが可視化できないと不便だと思って調べました。

環境

Rails 5.2.3
jQuery

留意点

htmlはhamlで記述。

コード

new.html.haml
%input#passcheck{:type => "checkbox"}
sign_up.js
$(document).on('turbolinks:load', function() {
  $(function() {
    $('#passcheck').change(function(){ // passwordの切り替え
      if ( $(this).prop('checked') ) {
          $('.password').attr('type','text');
      } else {
          $('.password').attr('type','password');
      }
    });
  });
});

htmlに表示切り替え用のチェックボックスを作り、イベント発火用にidを付与します。
Javascriptのchangeイベントで表示の切り替えをしますが、この時、propメソッドでチェックボックスの状態を判別します。
最後にattrメソッドでtypeをtextかpasswordに変更します。
typeが変わっても中身のテキストは消されないのが便利でした。

propメソッド
prop(attr)の使い方にも書かれているように、propメソッドは「checked」や「disabled」などのプロパティを使って条件分岐するようなケースで使い、結果として、trueかfalseを返してくれます。

実行結果

demo

自分のアプリケーションではチェックボックスにbootstrapのtoggleを適用させているのでこのような見た目になっています。

参考サイト

jQueryやJavaScriptでパスワードフィールドの文字を表示する方法

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?