Update URL when searching

This commit is contained in:
Alexandre Iooss 2020-08-22 09:35:55 +02:00
parent 8465b24d7d
commit 2272cf5294
1 changed files with 27 additions and 10 deletions

View File

@ -12,7 +12,8 @@ SPDX-License-Identifier: GPL-3.0-or-later
{{ title }}
</h3>
<div class="card-body">
<input id="searchbar" type="text" class="form-control" placeholder="{% trans "Search by attribute such as name" %}">
<input id="searchbar" type="text" class="form-control"
placeholder="{% trans "Search by attribute such as name…" %}">
</div>
<div id="dynamic-table">
{% if table.data %}
@ -30,8 +31,6 @@ SPDX-License-Identifier: GPL-3.0-or-later
{% block extrajavascript %}
<script type="text/javascript">
let pattern = '';
function reloadTable() {
pattern = $("#searchbar").val();
@ -46,21 +45,39 @@ SPDX-License-Identifier: GPL-3.0-or-later
});
// Highlight searched terms
$("tr").each(function () {
$(this).find("td:eq(0), td:eq(1), td:eq(2), td:eq(3), td:eq(5)").each(function () {
$(this).html($(this).text().replace(new RegExp(pattern, 'i'), "<mark>$&</mark>"));
const pattern = $("#searchbar").val();
if (pattern.length > 2) {
$("tr").each(function () {
$(this).find("td:eq(0), td:eq(1), td:eq(2), td:eq(3), td:eq(5)").each(function () {
$(this).html($(this).text().replace(new RegExp(pattern, 'i'), "<mark>$&</mark>"));
});
});
});
}
}
$(document).ready(function () {
let pattern = '';
// Recover last search from url
let searchParams = new URLSearchParams(window.location.search)
if (searchParams.has('search'))
if (searchParams.has('search')) {
pattern = searchParams.get('search');
}
// On search, refresh table
$("#searchbar").keyup(debounce(reloadTable, 300));
$("#searchbar").keyup(debounce(function () {
// Get new pattern
pattern = $("#searchbar").val();
// Set URL
searchParams.set('search', pattern);
history.pushState({}, null, "?" + searchParams.toString());
// If long enough, update table
if (pattern.length > 2) {
$("#dynamic-table").load(location.pathname + "?search=" + pattern.replace(" ", "%20") + " #dynamic-table", init_table);
}
}, 300));
// First init
init_table();