JQuery
[jQuery]検索フォームをjQueryで実装
ヤス
更新日:2021/08/12
サーバーに負担をかけたくない時には、jQueryに頼ることが多いです。
検索したいけどブラウザ側で完結したい
tableの検索を実装する際に、行数が100程度だったのでサーバーにリクエストにせずにjQueryで検索できるようにしてみました。
(行数が多い場合はサーバーにリクエストして検索結果を表示した方がいいかもしれません)
jQuery設定
<input>タグのtype属性がsearchの場合、入力があると自動でtableを検索し一致した行のみ表示します。
var search_word;
$("input[type='search']").on('keyup change blur',function(){
//一旦全部表示する
$('.table tr').show();
$("input[type='search']").each(function(){
if($(this).val()){
search_word = $(this).val();
//検索したいワードと一致しない場合表示を隠す
$('.'+$(this).attr("name")).filter(function(){
return $(this).html().match(new RegExp(search_word,"i")) === null;
}).parent().hide();
}
});
});
検索フォーム設定
検索したい項目に対してclass名を設定することで検索できます。
class名で検索することで複雑な検索に対応できます。
ID検索:<input type="search" name="id" value="" /> 名前検索:<input type="search" name="name" value="" /> <table class="table" border="1"> <tr> <th>ID</th> <th>名前</th> </tr> <tr> <td class="id">1</td> <td class="name">太郎</td> </tr> <tr> <td class="id">2</td> <td class="name">花子</td> </tr> </table>
まとめ
今回はtableのみでしたが、リスト等でも対応できます。