The dropdown Select2, filled from JSP/Ajax, loses functionality after initial use with a button

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:

  1. Saving the initial select content into a variable:

    const fpa = $("#selectFPA").find("option").clone();

  2. 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.

Answer №1

According to information provided in this response, it seems creating constants in jQuery may not be possible, explaining why it only works the first time and fails on subsequent attempts. An alternative approach could involve assigning the 'clone' value to a 'div' element and retrieving it whenever necessary. Here's an example:

// Executed when the page is loaded for the first time
$(document).ready(function() {
  // Cloning process
  var fpa = $("#selectFPA").find("option").clone();
  // Assigning cloned value to the div
  $("#abc").html(fpa);

  $("#ResetFilters").on("click", function() {

    // Retrieving the cloned value from the div
    var c = $("#abc").find("option").clone();
    // Clearing the content initially
    // $('#selectFPA').empty().trigger('change.select2');
    // Replacing with the original value
    $("#selectFPA").html(c);
    //$('#selectFPA').trigger('change.select2')
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectFPA" name="selectFPA" form="formResult" class="form-control">
  <option selected>All the results</option>
  <option>1</option>
  <option>2</option>

</select>

<button id="ResetFilters">Reset</button>
<div id="abc" style="display:none"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sending a significant quantity of JSON data (excluding files) using Node.js/Express

I have encountered an issue with my ajax(jquery) post function that involves uploading a large amount of JSON data. The data is chunked when posted, requiring us to monitor data requests and compile a complete buffer of the upload data. This is how it&apos ...

Learn how to create a registration form using Ajax, PHP, and MySQL

So far I've been working with HTML <form id="account_reg" action="reg.php" method="post"> <div id="response"></div> <div class="input"> <label>Login</> <input name="login" type="text" class=" ...

HTML - Selecting Different Values in One Drop Down Based on Another Drop Down

When selecting "First Year" in the initial drop-down menu, the options "Sem1" and "Sem2" should be displayed in the second drop-down menu. Similarly, when choosing "Second Year" in the first drop-down menu, the choices "Sem3" and "Sem4" should appear in th ...

Concealing video when the source is inaccessible

I am facing an issue with a video element that retrieves its source from a database. The video tag is placed inside a repeater that is bound to the database. My goal is to hide the video if the source is not found in the database. I attempted to use Javasc ...

The functionality of the Bootstrap carousel appears to be malfunctioning

My attempt at creating a carousel has hit a snag - it seems to be stuck on the first image and the next and previous buttons aren't functioning. I've gone over the code multiple times, but I just can't pinpoint the issue. Any assistance woul ...

Refresh all div elements if included in the results of the $.ajax call

My ajax function retrieves html content with div elements. However, Internet Explorer tends to include comments in the result array without an id, leading to errors like "object doesn't support this property or method". Removing the comments resolves ...

Best practices for securing Firebase Database

So, here's the scenario - we need to save data from a form to Firebase. The backend work is managed by Express. Time is of the essence here, so I want to make sure I get it right the first time. Right now, I've set the rules to allow both read ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Guide on integrating next-images with rewrite in next.config.js

I'm currently facing a dilemma with my next.config.js file. I've successfully added a proxy to my requests using rewrite, but now I want to incorporate next-images to load svg files as well. However, I'm unsure of how to combine both functio ...

Is there a way to eliminate the auto-opening feature of WordPress Shortcode Ultimate Accordion on mobile devices with the help of jquery

Currently, I am utilizing the Accordion feature of Wordpress Shortcode Ultimate plugin. Although the plugin does offer an option to open the accordion on page load, I would like to have them closed by default on mobile devices. How can I achieve this usin ...

Bluebird Enthusiastically Predicting the Outcome of a Complex Operation

Lately, I've been heavily utilizing Bluebird in my HAPI API development. However, I've encountered a perplexing issue that has left me puzzled due to either my understanding or lack of experience. Below is an example demonstrating the challenge ...

Stopping repeated content with endless scrolling ajax spinner

It seems like my mind is too foggy from the late night hours to find a clear solution, so I thought I'd seek some input from those who have an opinion... The website project I'm currently working on features a lengthy list of user posts. I' ...

When accessing WordPress through a URL, I am able to view regular PHP files but encounter difficulty accessing any uploaded files

Currently working on a Wordpress project and facing issues with creating a product via the WooCommerce REST API. I managed to make it work in my local environment, but upon uploading the files to the server, I am unable to reach a specific file via URL. Fo ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

AngularJS route not being resolved upon initial page rendering

Looking to integrate an AngularJS router into my application, I've defined a route in angular.module('MyModule').config(): $routeProvider .when('/:stepId?', { templateUrl: EditorApp.webDir + 'bundles/innovapath/a ...

Guide on making API calls in AngularJS using query strings

I am new to learning about AngularJS and recently came across a helpful article on connecting to an API and using its data in our app. The article specifically focuses on displaying weather information with AngularJS. The only downside is that the weather ...

Exploring the concept of D3 data binding key accessor

Exploring D3 for the first time, I am working on a basic example to grasp the concept of data binding. My setup includes an array of colors, a function to add a color, and a function to remove a color based on index. However, I'm facing issues with t ...

Error encountered in jsonwebtoken payload

Working on a web application with nodejs and angular cli, I have implemented JWT for login authentication. However, during the processing, I encountered the following error: Error: Expected "payload" to be a plain object. at validate (D:\Mean ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

Learn the process of updating database information with AngularJS through a button click

As a newcomer to Angular, I am facing an issue in my mini project. The main goal of the project is to display data from a database. I have successfully set up the view to show current data by making API calls and connecting to the database. However, I am n ...