Performing a search in Select2 only after all remote data has been loaded

The select2 feature is functioning almost as desired. It successfully loads all remote data and formats it correctly when another field is changed. However, I am looking to reintroduce the search function for the retrieved data. Specifically, once the data is fetched, I want users to be able to search the list by title (result.title).

In the provided example, the data is retrieved but the search term is not being filtered. It is crucial that all remote data be loaded before requiring users to search for a result.

If it is not possible to enable searching, how can I disable the search box? Even when setting "minimumResultsForSearch: -1", the select2 box still allows me to search?

https://i.sstatic.net/OwOv8.png

    var $company2 = $(".company2");
    $company2.select2().on('change', function() {
        if ($company2.val() !== null) {
            $('.unmaintained2').select2({
                allowClear: true,
                minimumResultsForSearch: 1,
                ajax: {
                    url: "/api/unmaintained2/" + $company2.val(),
                    processResults: function (data) {
                        return {
                            results: data,
                        };
                    },
                    dataType: 'json',
                    cache: true,
                },
                escapeMarkup: function(m) {
                    return m;
                },
                templateResult: function (result) {
                    if (result.loading) return 'Loading...';
                    return result.text + '<h6>' + result.make + ' ' + result.category + '</h6>';
                },
            });
        };
    });

Answer №1

Discover a feature called matcher for searching. For further details, refer to the documentation

However, this particular feature can only be utilized with locally provided data.

If you are working with remote data, select2 assumes that the data returned is already filtered.

The 'matcher' function exclusively functions with locally supplied data (e.g., through an array)! In cases where remote data sets are used, Select2 anticipates that the returned results have been pre-filtered on the server side.

It appears that using this method with the ajax option may not be viable.

An alternative approach could involve loading the data upon page initialization and subsequently integrating the retrieved data as options into the select box. Following this, the select2 box can be initiated with the matcher option.

UPDATE:

I experimented a bit and found a way to format the search results post loading all options. Take a look at this code:

function formatState (state) {
  if (!state.id) {
    return state.text;
  }
  var state1 = state.text + '<h6>(' + state.id  + ') ' + state.text + '</h6>';
  return state1;
};

function selection(state) {
    return state.text;
}

function makeSelect2(data) {
    $('#selectBox').select2({
        data: data,
        templateSelection: selection,
        templateResult: formatState,
        escapeMarkup: function (state) {
            return state;
        },
    });
}

$(document).ready(function() {
    $.ajax({
        type: "POST",
        dataType: "json",
        async: true,
        url: "ajax.php",
        data: ({ 
        }),
        success: function (data) {
            makeSelect2(data);
        }
    });
});

During $(document).ready, the options are fetched via ajax. Once the ajax call is successful, the function makeSelect2 is invoked with the data received from the ajax request. Within the makeSelect2 function, the select2 box is set up with the specified data and by utilizing the templateSelection and templateResult options, you have the ability to customize the appearance of your search results.

Hoping this aligns with your expectations.

Answer №2

Big shoutout to @dns_nx for providing the ultimate solution below! The select2 feature is now fully searchable on the client side and customizable with remote data!

$(document).ready(function() {
    var $company2 = $(".company2");
    var $equipment2 = $(".equipment2");
    $company2.select2().on('change', function() {
        $equipment2.empty();
        if ($company2.val() !== null) {
            $.ajax({
                url: "{{ url('/') }}" + "/api/unmaintained2/" + $company2.val(),
                type: 'GET',
                dataType: 'json',
                async: true,
                success: function(data) {
                    $equipment2.select2({
                        data: data,
                        templateSelection: function(result) {
                            return result.text;
                        },
                        templateResult: function(result) {
                            if (!result.id) {
                                return result.text;
                            }
                            var final = '<h2>'+ result.serial + '</h2><h5>(' + result.make  + ') ' + result.category + '</h5>';
                            return final;
                        },
                        escapeMarkup: function(result) {
                            return result;
                        },
                    });
                }
            });
        }
    }).trigger('change');
});

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

Challenges with React Native's AsyncStorage

When I try to access data stored in asyncStorage using the 'getToken' and 'getMail' functions in the code snippet below, I encounter an issue where the data appears empty when I initially open the page on the emulator. However, upon sav ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Implementing TypeScript with styled components using the 'as' prop

I am in the process of developing a design system, and I have created a Button component using React and styled-components. To ensure consistency, I want all my Link components to match the style and receive the same props as the Button. I am leveraging t ...

Changing the location.hash parameter prior to the page loading

Imagine a scenario where a page contains only the following script: <script type="text/javascript"> window.location.hash = 'testing'; window.history.back(); </script> When you navigate to google.com and then load this page, you& ...

Using the TypeScript compiler API to determine the location in the generated code of a particular AST node

I am aiming to retrieve the specific TypeScript AST node's location (start and end) in the emitted JavaScript file. Consider this code snippet: const program = ts.createProgram(tsconfig.fileNames, tsconfig.options); const aNode = program.getSourceFi ...

The jQuery functions seem to be malfunctioning when trying to retrieve elements by their ids

I'm having trouble with the click function when using IDs, but it works fine with classes. $('#myTab li a').click(function(e) {} When I switch to using classes like this: $('.nav-tabs a.overview').click(function(e) {} it work ...

How to locate the data-id of the next element in a jQuery list

Is it possible to retrieve the data-id of the following list element when clicking a button while on the current active list item? <div class="nbrs"> <ul> <li id="item1" data-id="1" class="active ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...

Can the settings of the Firefox browser be modified using a Vue.js application?

I utilized Kerberos for single sign-on (SSO) in my project. However, when making a request from the Vue.js client application to the Kerberos server, it does not work properly in Firefox due to disabled Kerberos support by default. This requires users to m ...

web address ajax search

Not sure what I'm searching for, so if you could help me identify what this is and suggest keywords to look up. http://website.com/page.php#article23 The number sign isn't a typical URL request method like GET or POST; it's more like an "A ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

Defending against the onslaught of quick and frequent ajax requests

In my game, a user can click a button to trigger a php function via ajax. This function records the call and reduces the user's ability to click the button by 1. If a user repeatedly clicks the button or forcefully calls the php function, they can ex ...

Display Descriptions Upon Hovering Over Images

I am attempting to utilize JavaScript to display the caption of an image only when it is being hovered over, and to have a default caption shown when no image is being hovered. <ul class="logos"> <li class="image-1"></li> <li ...

UnknownReferenceError: jwreload has not been declared (Exploring dynamic routing in next.js)

Error in dynamic route with next.js Recently, I started learning next.js and encountered an issue while implementing a dynamic route. The error message "ReferenceError: jwreload is not defined" keeps appearing whenever I reload the page. Surprisingly, des ...

javascript: extracting class name from HTML elements

To extract class names from an HTML code using JavaScript, I can utilize the following method: var cPattern = new RegExp(/class[ \t]*=[ \t]*"[^"]+"/g); var cMatches = data.match(cPattern); However, the above code returns an array with values li ...

Bidirectional communication between two AngularJS scopes or controllers utilizing a service

I am facing numerous situations where I require clicks or other interactions to trigger actions in a different area of the webpage (one-way communication). Now, I have encountered a need for bidirectional communication, where changes made in element A can ...

Hide the overlay fullscreen menu upon clicking an anchor link

I'm having trouble with Javascript, but some of you might find this easy. I found a fullscreen overlay menu on Codepen and I'm trying to figure out how to close it when clicking an anchor link. Looking for assistance with adding javascript to c ...

Incorrect positioning on canvas

Is there a way to adjust text alignment within a canvas? Currently, my text is centered. However, when I change the text size, the alignment gets thrown off. Here is the code snippet: <canvas id="puzzle" width="480" height="480"></canvas> ...

What should we name this particular style of navigation tab menu?

What is the name of this tab menu that includes options for next and previous buttons? Additionally, is there a material-ui component available for it? https://i.sstatic.net/0m9rH.png ...

Upgrade your react-select by replacing the DropdownIndicator with a modern CSS triangle design

I am a beginner in React and JS, and I am facing a challenge that I need to solve. My task is to replace the DropdownIndicator with a CSS triangle. While I have come across some similar issues (such as this one https://github.com/JedWatson/react-select/iss ...