0
0

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 3 years have passed since last update.

【jQuery】フォームからフォーカスが外れたら値を整形する

Posted at

環境

Rails 6
jQuery

Solve

test.gif

  • フォーカスが外れたら前後の空白を削除して全角空白を半角空白へ置換
  • フォーカスが外れたら小文字のアルファベットを大文字に変換

utilに書いた共通メソッドをincludeしてview側で必要なものだけ呼び出せます。
引数はid等セレクタを渡します。複数可。

util.js
// 名前空間
var myUtil = {

  /**
   * フォーカスが外れたら前後の空白を削除して全角空白を半角空白へ置換
   * @param selectors {String} 文字列形式のセレクタ
   */
  trimBlank: function(selectors) {
    $(selectors).focusout(function(e) {
      var oriStr = $(this).val().replace(/ /g, " ");
      $(this).val($.trim(oriStr));
    });
  },

  /**
   * フォーカスが外れたら小文字のアルファベットを大文字に変換
   * @param selectors {String} 文字列形式のセレクタ
   */
  convertUppercase: function(selectors) {
    $(selectors).focusout(function(e) {
      var oriStr = $(this).val();
      $(this).val(oriStr.toUpperCase());
    });
  },

}

window.myUtil = myUtil;
application.js
require('./custom/util')
_xxx_form.html
<script>
  // 共通メソッド呼び出し
  $(function(){
    myUtil.trimBlank('#mail, #name');
    myUtil.convertUppercase('#name-en');
  });
</script>
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?