How can I disable certain options with Select2 and remote data
Asked Answered
P

2

13

Select2 supports disabled options when it is initialized on a <select> tag, as discussed in this issue

However, I can't find how to achieve the same result with remote data. Do I need to use a custom format function? How do I prevent the user from selecting it then? Or is this built-in somewhere?

Thanks!

Phia answered 14/8, 2013 at 11:30 Comment(0)
D
34

In Select2 3.4.2 you just need to add a disabled: true property to the given result object. Practical example with a query function:

$('input').select2({
    query: function(query) {
        //do ajax call which retrieves the results array in this format:
        var data = {results: [
            { id: 1, text: 'disabled option', disabled: true },
            { id: 1, text: 'hi' }
        ]};
        //pass it to the query callback inside your Ajax callback:
        query.callback(data);
    }
});

Demo


The same can be done using the ajax wrapper, which accepts a result objects array in the same format as the query function.

Here's a demo with an actual Ajax call (through jsFiddle's JSON API):

$('input').select2({
    ajax: {
        url: '/echo/json/',
        dataType: 'json',
        params: {
            method: 'post'
        },
        data: function (term, page) {
            // Data to be sent to the server. Usually it is just the "term"
            // parameter (and page if using pagination).
            // However, since this API simply echoes back what we send,
            // I'll build the results array here
            var resultsArr = [];
            for (var i = 0; i < 10; i++) {
                resultsArr.push({
                    id: i,
                    text: 'opt'+i,
                    //randomly disable a couple options for demo purposes
                    disabled: Math.random() < .3
                });
            }
            return {
                json: JSON.stringify(resultsArr)
            }
        },
        results: function(data, page) {
            //data param === received response from the server. As dataType
            //is json, jQuery automatically parses the response into an object.
            //So, in this case, we received the resultsArr that we sent.
            //Now return it in the correct format: { results: resultsArr }
            return { results: data };
        }
    }
});

Demo

Remember that the data function in this last example is just to properly use the jsFiddle API - you should keep your original data function which sends the query term. All you have to do is modify the response so that the result objects include a disabled: true property in the results that you want to be disabled, in the same format as the first example.

Degauss answered 18/8, 2013 at 1:25 Comment(7)
Will try this out first thing tomorrow! Good gosh, if that really works I can't believe it was that simple. Can I just ask one question: how did you know to add this "disabled" property? Did you find this in the docs, or was it an educated guess?Phia
@Phia No problem. =] I contribute to the Select2 project every now and then, so I'm rather familiarized with its source - it was easy to find where it checks for the disabled property (here). But you're right, this option is kinda hidden, I'll send a PR to update the docs later today. :PUngovernable
Alright thanks! I can't award my bounty yet (2 hours remaining) and it's getting late where I live, so you should be getting that first thing tomorrow as well. Thanks for the answer! While it's really simple, I love how you wrote out entire examples. You earned the bounty for sure. :-)Phia
Okay no rush, g'night. =] I've contacted Igor through your GH issue, I'll send a doc update pull request once I manage to document it properly.Ungovernable
BTW I've made a PR to document this but had no reply yet.Ungovernable
@Dementic External resources are pretty much expected to rot away, that is why answers include all the relevant code. Anyway, I've fixed the fiddles, thanks for reporting.Ungovernable
also, the selected prop is work with disabled for default display, just like the option html tagRabblerouser
S
3

select2 can't change the server data, but you can change options before the result reloaded to the page

  $('.input-selector').select2({
  ajax: {
      url: function (params) {
        return '/to/url/resource.json';
      },
      processResults: function (data) {
        var data_modified = $.map(data.results, function (obj) {
          obj.disabled = true; // or use logical statement
          return obj;
        });

        return { results: data_modified };
      }
    }
  });
Sicanian answered 11/7, 2020 at 3:7 Comment(2)
Thanks... I didn't find this on documentation.Phrygia
sure. with my pleasureSicanian

© 2022 - 2024 — McMap. All rights reserved.