← 動的パーツギャラリーへ戻る

パーツ番号 04-03-03 ・ JavaScript使用

オートコンプリート候補リスト

入力に応じて候補が下に絞り込まれて表示される検索補助UI。Contact Form 7の住所入力やお問い合わせ項目選択の入力補助に活用できます。

jsinput

プレビュー

ソースコード

HTML

<div class="d04-03-03-wrap">
          <input class="d04-03-03-input" type="text" placeholder="都道府県名を入力" autocomplete="off">
          <ul class="d04-03-03-list"></ul>
        </div>

CSS

.d04-03-03-wrap{position:relative;width:min(280px,100%)}
        .d04-03-03-input{
          width:100%;padding:12px 14px;font-size:14px;box-sizing:border-box;
          border:2px solid #d5d9e0;border-radius:8px;outline:none;background:#fff;
          transition:border-color .2s;
        }
        .d04-03-03-input:focus{border-color:#4a6cf7}
        .d04-03-03-list{
          position:absolute;top:calc(100% + 6px);left:0;right:0;z-index:5;
          margin:0;padding:6px;list-style:none;background:#fff;
          border:1px solid #e2e6ee;border-radius:10px;
          box-shadow:0 10px 25px rgba(30,40,80,.15);
          display:none;max-height:180px;overflow:auto;
        }
        .d04-03-03-list.is-open{display:block}
        .d04-03-03-list li{
          padding:9px 10px;font-size:13px;color:#444;border-radius:7px;cursor:pointer;
        }
        .d04-03-03-list li:hover{background:#eef2ff;color:#4a6cf7}

JavaScript

(function(){
        var wrap=document.querySelector('.d04-03-03-wrap');
        if(!wrap)return;
        var input=wrap.querySelector('.d04-03-03-input');
        var list=wrap.querySelector('.d04-03-03-list');
        var data=['東京都','大阪府','愛知県','福岡県','北海道','沖縄県','神奈川県','京都府','広島県','宮城県'];
        input.addEventListener('input',function(){
          var v=input.value.trim();
          list.innerHTML='';
          if(!v){list.classList.remove('is-open');return;}
          var hits=data.filter(function(d){return d.indexOf(v)!==-1;});
          if(!hits.length){list.classList.remove('is-open');return;}
          hits.forEach(function(h){
            var li=document.createElement('li');
            li.textContent=h;
            li.addEventListener('click',function(){
              input.value=h;
              list.classList.remove('is-open');
            });
            list.appendChild(li);
          });
          list.classList.add('is-open');
        });
        document.addEventListener('click',function(e){
          if(!wrap.contains(e.target))list.classList.remove('is-open');
        });
      })();

クラス名 .d04-03-03 は本ライブラリ内での識別用です。複数のパーツを同じページで使う場合は、重複しないよう名前を変更してください。