Railsでインクリメンタルサーチを作った時のコードを使いやすく切り出してみました。
※インクリメンタルサーチ: 入力のたびに自動的に検索をする検索方法 (例: Google検索)
何ができるの?
• テキストボックスに入力があった時にコールバック関数を呼び出す
• サーバーへの負荷を抑えるために入力をやめるまで検索をしない
前提
- 検索自体はサーバー側で行う
- jQueryを利用している
コピペ用コード
isearch.js
var ISearch = ISearch || {};
ISearch.setup = function(textfield, callback, options) {
var timer = null, lastInput = '';
wait = 500;
minLength = 0;
if (options !== undefined) {
wait = options.wait;
minLength = options.minLength;
}
textfield.on('keyup', function() {
var input = $.trim($(this).val());
if (lastInput !== input && input.length >= minLength) {
clearTimeout(timer);
timer = setTimeout(function() {
callback(input);
}, wait);
}
lastInput = input;
});
};
使い方
app.js
var textfield = $('#search'); // <input type="text" id="search">
// 例: 本の検索
ISearch.setup(textfield, function(input) {
$.get("search_book", { q: input }
).done(function(books) {
$("#books").html(books);
});
});
// 入力待機時間を1秒に変更
ISearch.setup(textfield, function(input) {
// search
}, { wait: 1000 });
// 3文字以上入力されるまで検索しない
ISearch.setup(textfield, function(input) {
// search
}, { wait: 1000, minLength: 3 });