select2 from json based on other input field

老子叫甜甜 提交于 2019-12-24 18:29:40

问题


I need to populate a CITY select based on selection on PROVINCE with select2.

I've some problems:

1- PROVINCE: It's populated by default, but i get duplicate elements. In my example i get:

Milan
Milan
Torin
Torin

but i'd like to get:

Milan
Torin

Solved by @david: http://jsfiddle.net/pe1u6Luo/282/

2- Based on PROVINCE select, i need to populate CITY ONLY with subarray. For example if I select Milan on first select, i need to get CITY like:

Rho
Other city

I don't know how to filter.

Solved by @david: http://jsfiddle.net/pe1u6Luo/282/

3- Fieldbox filter of select2 doesn't work. If I insert "MI", Torin still display

4- Based on @david solution http://jsfiddle.net/pe1u6Luo/282/, i've to return PROVINCE array in alphabetically order. In my example is already done cause i've only 2 items inserted and already ordered..

This is my original fiddle:

http://jsfiddle.net/pe1u6Luo/218/


回答1:


Add if statement on your processResults.

Check the processResults in the province.

processResults: function (data) {
    var a = [];
    return {
        results: $.map(data, function(obj) {
            if (!a.includes(obj.provincia.nome)) {
                a.push(obj.provincia.nome);
                return { id: obj.provincia.codice, text: obj.provincia.nome };
            }
        })
    };
}

This is the processResults in the city selection.

processResults: function (data) {
    return {
        results: $.map(data, function(obj) {
            if ($('#province').val() == obj.provincia.codice){
                return { id: obj.nome, text: obj.nome };
            }
        })
    };
}

In the province selection, declare an array for storing the province name. If a province name is already inside the array, don't show the duplicate.

In the city selection, just check the province code with the selected province code.




回答2:


Its an issue related to the object that you are reading. The object that is being parsed has provincia.name = 'Milan' at two places and 'Torin' at two places.

The select2 functionality is working fine, the issue is with the object being 'read'.



来源:https://stackoverflow.com/questions/51241676/select2-from-json-based-on-other-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!