LoginSignup
2
0

More than 5 years have passed since last update.

エントリーシートで文字数確認用のボタンをいちいち押させるな

Last updated at Posted at 2019-03-15

目的

文字数制限があるのに、文字数をリアルタイム表示してくれないエントリーシートのなんと多きことよ。
textarea, input[type='text']の近くに文字数を表示させたろ!!(むしろ最初から表示してくれよ)
アドオンかブックマークレットのどちらか・・・。今回はブックマークレットにしよう。

ブックマークレット

javascript:(function(b){if(window.jQuery&&2<=window.jQuery().jquery[0])b(jQuery);else{var a=document.createElement("script");a.src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js";a.onload=function(){b(jQuery.noConflict(!0))};var c=document.body;c.appendChild(a);c.removeChild(a)}})(function(b){["textarea","input[type='text']"].forEach(function(a){b(a).each(function(a,d){var c=document.createElement("span");d.insertAdjacentElement("beforebegin",c);d.insertAdjacentElement("beforebegin",document.createElement("br"));var e=function(){c.textContent=d.textLength};e();b(d).bind("input propertychange",e)})})});

元コード

((func) => {
  if(window.jQuery && (window.jQuery().jquery[0] >= 2)) {
    func(jQuery);
  } else {
    let scr = document.createElement("script");
    scr.src = "//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js";
    scr.onload = () => {
      func(jQuery.noConflict(true));
    };
    let bd = document.body;
    bd.appendChild(scr);
    bd.removeChild(scr);
  }
})(($) => {
  ["textarea", "input[type='text']"].forEach((selector) => {
    $(selector).each((i, t) => {
      let span = document.createElement("span");
      t.insertAdjacentElement("beforebegin", span);
      t.insertAdjacentElement("beforebegin", document.createElement("br"));
      let f = () => { span.textContent = t.textLength; };
      f();
      $(t).bind("input propertychange", f);
    });
  })
});

概説

  • 前半部分:引数として渡される関数を実行するjQueryの設定
    • jQueryが存在する && ページのjQueryのバージョンが2以上 ?
      • true → 存在するjQueryで関数を実行
      • falsev3.2.1を読み込み関数を実行 && 読み込んだjQueryを削除
  • 後半部分:リアルタイム文字数表示の実装
    • "textarea", "input[type='text']"に該当する要素に対して
      • 要素の前に<span>(と<br>)を生成
      • 入力箇所の変化をバインドして、<span>の文字を置換

参考

2
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
2
0