サンプルコード
html
<label for="search-input">Search:</label>
<input type="text" id="search-input" />
<table id="my-table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
// CSVデータを取得する
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function(csvData) {
// CSVデータを配列に変換する
const rows = csvData.split('\n');
const headers = rows[0].split(',');
const data = [];
// ヘッダとデータを分割する
for (let i = 1; i < rows.length; i++) {
const row = rows[i].split(',');
if (row.length === headers.length) {
const obj = {};
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = row[j];
}
data.push(obj);
}
}
// 指定したカラムのみを抽出する
const columns = ["Name", "Age", "Gender"];
const filteredData = data.map(obj => {
return columns.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
});
// テーブルを作成する
const table = $('#my-table tbody');
$.each(filteredData, function(index, row) {
const tr = $('<tr>');
$.each(columns, function(i, column) {
$('<td>').html(row[column]).appendTo(tr);
});
table.append(tr);
});
// テーブルをフィルタする関数
function filterTable() {
// テーブル、検索語句を取得する
const table = $('#my-table');
const searchQuery = $('#search-input').val().toLowerCase();
// テーブルの各行をチェックして、検索語句にマッチするものだけを表示する
table.find('tr').each(function(index, row) {
const allCells = $(row).find('td');
if (allCells.length > 0) {
const found = allCells.filter(function(index, td) {
const cellText = $(td).text().toLowerCase();
return cellText.indexOf(searchQuery) > -1;
}).length > 0;
if (found) {
$(row).show();
} else {
$(row).hide();
}
}
});
}
// フィルタを実行するイベントハンドラ
$('#search-input').on('keyup', filterTable);
}
});