In my webpage, there are 12 filters that query a database using select2 dropdowns.
Upon page load, the selects are automatically populated with data from a java controller.
Here's an example snippet from a JSP page:
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
<option selected>All the results</option>
<c:forEach items="${fpaList}" var="fpaList">
<option><c:out value="${fpaList.fpaname}" /></option>
</c:forEach>
</select>
Whenever a user selects a value in any of the filters, all other filters get updated based on the selected item through AJAX calls.
For instance, let's say we have two select filters:
Select 1 (Animal group): - Birds - Mammals
Select 2 (Animal name): - Parrot - Dog
If the user picks mammals, an AJAX call will refresh the content of select 2, removing the Parrot option. This process continues for up to 12 filters.
The challenge arises when trying to reset the filters and revert back to the original select content retrieved from the java controller.
I've attempted various solutions found on Stackoverflow without success.
The most recent solution involved:
Saving the initial select content into a variable:
const fpa = $("#selectFPA").find("option").clone();
Creating an onclick event for the Reset Filters button
$("#ResetFilters").on("click",function() {
//empty the content
$('#selectFPA').empty().trigger('change.select2');
//restore original values
$("#selectFPA").html(fpa),
$('#selectFPA').trigger('change.select2')
})
This approach works correctly upon first click, but if clicked again, the selects seem to randomly choose default values and behave oddly.
I understand this is a specific issue, but could someone provide guidance on what might be going wrong?
Thank you.