使用多个本地JSON数组作为结果的JQUERY自动完成

时间:2015-03-30 16:27:19

标签: javascript jquery json

使用JQUERY Autocomplete,我想根据其他一些用户选择触发的函数调用,用JSON_1或JSON_2替换源数据。我不想向服务器发出GET请求。我想要一个类似于

的加载函数
 function loadAutoComplete(sourceType){
    if (sourceType == "JSON1" ) {
       //Load Autocomplete with JSON_1 Data;
    }else{
       //Load Autocomplete with JSON_2 Data;
    }
 }



//JSON_1 and JSON_2 are populated at onload with a GET Request

JSON_1 = "[{"value":"-1","label":"(0000:0000) No Filter"},{"value":"-6585:QAP","label":"(-6585\/QAP) Acme QAP - "},{"value":"6235:QAP","label":"(6235\/QAP) Weaver and Tidwell L.L.P. - "},{"value":"6244:QAP","label":"(6244\/QAP) EcoEngineers - "},{"value":"6246:QAP","label":"(6246\/QAP) Genscape QAP - "},{"value":"6247:QAP","label":"(6247\/QAP) RINtrust QAP - "}]";

    JSON_2 = "[{"value":"-1","label":"(0000:0000) No Filter"},{"value":"3017:80107","label":"(3017\/80107) Texas Green Manufacturing LLC - Texas Green Manufacturing"},{"value":"3052:70005","label":"(3052\/70005) VITOL INC - VITOL \/PADD V (RFS2)"},{"value":"3052:70115","label":"(3052\/70115) VITOL INC - KINDER MORGAN - CARSON"}]";



        $("#filterCIDFID").autocomplete({
                //minLength: 0,

                source: function (request, response) {
                    //alert(ac_data);
                    response(ac_data);
                },
                focus: function (event, ui) {
                    $("#filterCIDFID").val(ui.item.label);
                    return false;
                },
                select: function (event, ui) {
                    $("#val_filterCIDFID").val(ui.item.value);
                    return false;
                }
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>").append("<a>" + item.label + "</a>").appendTo(ul);
            };

感谢任何和所有帮助。 谢谢J

1 个答案:

答案 0 :(得分:0)

$( “#filterCIDFID”)自动完成({});在呈现页面时触发。在渲染时,它将源文件附加到指定的#ID。

我首先将自动完成设置为'默认'源。

然后在选择应该更改自动完成源的其他按钮时,销毁自动完成并使用新来源再次添加

$( "#filterCIDFID" ).autocomplete({
//this is your default source
  source: [ "stuff", "cool", "default", "notthesame", "chicken", "pot", "pie" ]
});

$('#someuserselection').on('change', function() {
 if($(this).val()=='use_other_source'){
   $( "#filterCIDFID" ).autocomplete( "destroy" );
    $( "#filterCIDFID" ).autocomplete({
      //this is your OTHER source
       source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
    });
}
});