JavaScript)「ブログ記事一覧」の検索ボックスの文字列を、URLに反映できるようにした。ChatGPT(3.5)に教えてもらった。(コード生成)
以前に、『はてなブログ「晴歩雨描」記事一覧』ページ
https://ok2nd.github.io/sitemap/hatena-sitemap-table.html
のURLで、検索文字列を初期設定できるようにした。URLのパラメーター文字列を検索テキストボックスに反映させるもの。
今回逆に、検索テキストボックスに入力されている文字列を、URLのパラメーター(?search=文字列)に反映する機能を追加。
以下の方法をベースに、jQueryプラグイン「DataTables」の<INPUT>テキストボックス連携機能を追加。
URLパラメーターと検索ボックス間で双方向に文字列が反映される。
これについても、ChatGPT(無料版3.5)に教えてもらった。ググるより速い。
https://ok2nd.github.io/sitemap/hatena-sitemap-table.html?search=神戸

≪該当部分のスクリプト≫
<script type="text/javascript">
$(document).ready(function () {
// DataTablesの初期化
var table = $('#dataTable').DataTable({
language: { // 日本語化
"sProcessing": "処理中...",
"sLengthMenu": "表示 _MENU_ 件",
"sZeroRecords": "検索結果がありません",
"sInfo": " _TOTAL_ 件中 _START_ から _END_ まで表示",
"sInfoEmpty": " 0 件中 0 から 0 まで表示",
"sInfoFiltered": "(全 _MAX_ 件より抽出)",
"sInfoPostFix": "",
"sSearch": "検索:",
"sUrl": "",
"oPaginate": {
"sFirst": "先頭",
"sPrevious": "前",
"sNext": "次",
"sLast": "最終"
}
},
paging: false, // ページングしない。
ordering: false, // ソートしない。
mark: true // 検索文字列ハイライト (by mark.js)
});
// DataTablesが生成する検索ボックスを取得
var searchInput = $('div.dataTables_filter input');
// ↑INPUTボックス名はテーブル名+"_filter"になる
// ページの読み込み時にURLからパラメーターを読み取って検索フィルターに反映
var urlParams = new URLSearchParams(window.location.search);
var searchParam = urlParams.get('search');
if (searchParam !== null) {
searchInput.val(decodeURIComponent(searchParam));
table.search(decodeURIComponent(searchParam)).draw();
}
// テキストボックスの入力が変更されたときにURLを更新(?search=xxx)
searchInput.on('input', function () {
var inputTextValue = $(this).val();
var currentURL = window.location.href;
if (currentURL.indexOf('?') !== -1) {
// パラメーターがすでに存在する場合は置き換える
var updatedURL = currentURL.replace(/(\?|&)search=.*?(&|$)/, '$1search=' + encodeURIComponent(inputTextValue) + '$2');
} else {
// パラメーターが存在しない場合は新しく追加する
var updatedURL = currentURL + '?search=' + encodeURIComponent(inputTextValue);
}
// ブラウザの履歴を変更せずにURLを更新
window.history.replaceState({ path: updatedURL }, '', updatedURL);
// DataTablesの検索フィルターを更新
table.search(inputTextValue).draw();
});
});
</script>






