Simply I have a data which coming from jinja2. I want to filter data when I clicked the button. Another solution might be to pass the data to a javascript variable.
I have created an example for more clear definition. In this case I want to delete numbers which are less then 5. Then I list them in html.
In template;
{% set data = [1,2, 3, 4, 5, 6, 7, 8, 9] %}
<ul>
{% for item in data %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<button class="btn">Filter Data</button>
In Script
const btn = document.querySelector('.btn');
btn.addEventListener('click', () => {
// filter here
}
The simplest solution is that you also provide the data value as an attribute of the list item, e.g. data-index:
{% set data = [1,2, 3, 4, 5, 6, 7, 8, 9] %}
<ul class="mylist">
{% for item in data %}
<li data-index="{{ item }}">{{ item }}</li>
{% endfor %}
</ul>
<button class="btn">Filter Data</button>
Then you loop over the list items after the click event and based on the value of el.dataset.index, you can remove the respective items:
const btn = document.querySelector('.btn');
btn.addEventListener('click', () => {
let items = document.querySelectorAll(".mylist li")
Array.from(items, el => {
if (el.dataset.index < 5) {
el.remove()
// Or: el.style.display = 'none'
}
})
}