sksallaj
sksallaj

Reputation: 4010

Select2 4.0.0 cascading dropdowns

I'm using select2.full.js

I'm not using any require.js to help me pull in modules, I'm basically using my know how from everything I learned in v3.5

I've been trying countless of hours, wrapping my head around this, but I have no idea how to make ajax cascading dropdowns.

Example: You load up the page, there is the first select2 dropdown that pulls data using ajax automatically (you don't enter anything.. data is there on the page load from the server), a default value is selected. Since that default value is selected, the second select2 drop down will use that value to make an ajax call to populate its own list. Now, when I select another value in the first select2 dropdown, the second select2 dropdown will reflect those changes with the new dataset.

What I've able to come up with was a 3 dropdowns that you can populate on a page load, but when you do any ajax request, the dropdown data doesn't change.

It's been two years since I used select2, and the library keeps changing, the documentation keeps changing, I'm at my wits end with this library. But I feel drawn to it by the bootstrap support, and the look and feel. The functionality, the way to implement things, the documentation is just so unbelievably awful.

I don't have any useful code at all, I've been pulling, plugging, modifying, etc.. and now I'm moving to my hair and teeth.

ANY useful example to do this would be awesome.

Upvotes: 1

Views: 5598

Answers (2)

Anis
Anis

Reputation: 3599

Here is a small code snippet to make Select2 (v4.x) cascading dropdown - https://gist.github.com/ajaxray/187e7c9a00666a7ffff52a8a69b8bf31

Using this module, options of a select2 list box will be loaded/refreshed by ajax based on selection of another select2 list box.

Example use -

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

Selected value of parent select2 listbox will be set to the parent_id of the data object before ajax call.

Upvotes: 0

sksallaj
sksallaj

Reputation: 4010

Just found my answer..

I was using the templating:

<select id="test">
    <option value="1">1</option>
    <option value="2">2</option>
</select>

to:

data = [{id: "1", text: "1"}, {id: "2", text: "2"}];

<input id="test" type="hidden" />

and just kept my jquery on select2 the same. So it was really just a change in the templating from to that solved it.

However, the only downside to this is that when you are refreshing new data from these drop downs, the highlighted (selected value) is always the first item in the drop down list, even though that's not the selected value shown in the dropdown.

Upvotes: 0

Related Questions