Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 Dependent dropdown lists

I am trying to use the Select2 plugin to have 4 dropdown lists that depend on each other. I have struggled to find the right way to update the data that loads the options in.

My goal is to load the new data via ajax, but once I have it in the client I am unable to add the new data to the select list.

The code I have tried is here:

$(#"a3").select2({
    placeholder: "select an item",
    allowClear: true}).on("change",
    function (e) {
         var results = $.get("url?id=2",
            function (data, textStatus, jqXHR) {
                $(this).select2({ data: { results: data, text: "Name" } });
        });
    }
); 

There is another question here select2 changing items dynamically but the solution there worked with Select2 v3.2 but not Select2 v3.3

like image 809
Lee Baker Avatar asked Feb 10 '13 11:02

Lee Baker


People also ask

What is dropdownParent?

The dropdownParent option allows you to pick an alternative element for the dropdown to be appended to: $('#mySelect2'). select2({ dropdownParent: $('#myModal') }); This is useful when attempting to render Select2 correctly inside of modals and other small containers.

How do I create a dropdown Select 2?

Creating new options in the dropdown New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

What does select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


3 Answers

Igor has come back to me with a way to do this

var data=[...];    
$().select2({data: function() {return {results:data};}});    
/// later    
data=[...something else];    
// next query select2 will use 'something else' data
like image 134
Lee Baker Avatar answered Oct 14 '22 06:10

Lee Baker


The correct format is:

.select2("data", {...})
like image 42
igor.vaynberg Avatar answered Oct 14 '22 06:10

igor.vaynberg


For Select2 v4.x, here is a small js class.

Using this, options of a select2 list box will be loaded/refreshed by ajax based on selection of another select2 list box. And the dependency can be chained.

For example -

new Select2Cascade($('#country'), $('#province'), 'path/to/geocode', {type:"province", parent_id: ''});
new Select2Cascade($('#province'), $('#district'), 'path/to/geocode', {type:"district", parent_id: ''});

Check the demo on codepen. Also here is a post on how to use it.

like image 27
Anis Avatar answered Oct 14 '22 06:10

Anis