4
2

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.

datalist絞込

Last updated at Posted at 2017-10-26

datalist絞込

基本

html

type=searchでdatalistを設定してやると入力にあわせて絞込ができる

<input type="search" list="mylist" name="hoge">
<datalist id="mylist">
<option value="a1">
<option value="aa2">
<option value="aa3">
<option value="aaa4">
<option value="aab5">
<option value="b6">
<option value="b7">
</datalist>

ただし、ブラウザによっては上記サンプルで「b」を入力すると
「aab5」も「b」を含むためヒットしてしまう場合がある

拡張

javascript

javascriptで絞込を行う

document.addEventListener('input',function(e){
  var t=e.target;
  if(t.nodeName=="INPUT" && t.type=="search"){
    var v=t.value;
    var l=t.getAttribute('list');
    Array.prototype.map.call(document.querySelectorAll('#'+l+' option'),function(i){
      i.disabled=!i.value.match(new RegExp("^"+v));
      console.log(i.disabled);
    });
  }
});

jQuery

jQueryを使って書くとこんな感じ
(javascript版からさほど効率化しないのでjavascript版の方でいいかも)

jQuery
$(function(){
  $('input[type=search]').on('input',function(){
    var v=$(this).val();
    $('#'+$(this).attr('list')+" option").prop('disabled',function(){
      return !$(this).val().match(new RegExp("^"+v));
    });
  });
});
4
2
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?