Result
table内のすべてのテキストから検索し、該当箇所のある列を表示する、みたいなやつ
ある程度の量を持つデータテーブルだけど超大量でもないから、重いスクリプトは使いたくない、みたいな中途半端な状況の時は少ないコードで済ませたいところですね
vanillaなコードで動作します
JavaScript
( function (document) { 'use strict' ; var LightTableFilter = ( function (Arr) { var _input; function _onInputEvent(e) { _input = e.target; var tables = document.getElementsByClassName(_input.getAttribute( 'data-table' )); Arr.forEach.call(tables, function (table) { Arr.forEach.call(table.tBodies, function (tbody) { Arr.forEach.call(tbody.rows, _filter); }); }); } function _filter(row) { var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase(); row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row' ; } return { init: function () { var inputs = document.getElementsByClassName( 'light-table-filter' ); Arr.forEach.call(inputs, function (input) { input.oninput = _onInputEvent; }); } }; })(Array.prototype); document.addEventListener( 'readystatechange' , function () { if (document.readyState === 'complete' ) { LightTableFilter.init(); } }); })(document); |
html
< section class = "container" > < input type = "search" class = "light-table-filter" data-table = "order-table" placeholder = "検索" /> < table class = "order-table" > < thead > < tr > < th >名前</ th > < th >職業</ th > < th >住所</ th > < th >年齢</ th > </ tr > </ thead > < tbody > < tr > < td >はなこ</ td > < td >医師(いし)</ td > < td >新潟県(にいがた)</ td > < td >38</ td > </ tr > < tr > < td >たけし</ td > < td >海洋研究(かいようけんきゅう)</ td > < td >岡山県(おかやま)</ td > < td >48</ td > </ tr > ・ ・ ・ </ tbody > </ table > </ section > |