簡體   English   中英

使用JQuery Autocomplete使用數組和下拉列表

[英]Using JQuery Autocomplete using array and drop down list

我正在嘗試創建一個腳本,該腳本將使用JQuery的自動完成文本框來顯示按州過濾的數組中的縣數據。 狀態是一個下拉列表。 因此,例如:如果用戶為該州選擇了“伊利諾伊州”,則根據他們在文本框中鍵入的乞討字母,自動拼寫將為他們提供最接近的縣名。 我可以按狀態成功過濾陣列,然后使用正確的數據加載陣列,但是在嘗試將陣列加載到自動完成時遇到了問題。 這是代碼段。 非常感謝您的幫助:

    <body >
    <script type="text/javascript">


    function findCounties(State)
      {
var County = new Object();

var xmlhttp;
if (window.XMLHttpRequest)
{
    // code for IE7+, Firefox, Chrome, Opera, Safari

     xmlhttp = new XMLHttpRequest();
}
else
{
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

if (xmlhttp != null)
{
    xmlhttp.open("GET","US_Counties.csv",false); // the false makes this synchronous!
    xmlhttp.send();
    var text = xmlhttp.responseText;

    // text contains the ENTIRE CONTENTS of the text file
    // you *could* just write those contents directly to the HTML output:


    // but you might want to process that one line at a time.  if so:
    var lines = text.split("\n");

    var cntCounty = 0;
        for (var n=0; n<lines.length; n++)
        {
            if(lines[n].indexOf(State) > 0){
                var line = lines[n];
                var populate = line.split(',');


                County[cntCounty] = populate[1];
                cntCounty++;

            }//IF
        }//for
    $(function() {
            var Counties = [{
         a_state: []
        };
        for(var i in County) {

        var item = County[i];

            Counties.a_state.push({ 
            "label" : item.County
        "value" : item.County`enter code here`
        });
    ];

  j$("#counties").autocomplete({
    source: Counties 
  }).data("autocomplete")._renderItem = function(ul, item) {
    return $("<li>").data("item.autocomplete", item).append("<a>" + item.label ++ "</a>").appendTo (ul);
});

我使用了以下javascript代碼:

var stateList, countyList;

$(document).ready( function() {
    $.ajax({type: "GET",
            url: "US_counties.csv", // list of counties
            cache: false,
            error: function (xhr, textStatus, errorThrown) {
                window.alert(textStatus);
            },
            success: function (text, textStatus, xhr) {
                var s1 = $('#s1')[0]; // the select box
                stateList = [];
                // each line has one county on it
                $.each(text.split("\n"), function (ix, elt) {
                    var items = elt.split(','),
                        stateName = items[0],
                        countyName = items[3], a;
                    if (typeof stateList[stateName] == 'undefined') {
                        a = [];
                        a.push(countyName);
                        stateList[stateName] = a;
                        // add state to the select box
                        s1.options[s1.options.length] = new Option(stateName, stateName);
                    }
                    else {
                        stateList[stateName].push(countyName);
                    }
                });

                // set the change event handler for the dropdown
                $('#s1').bind('change', function() {
                    countyList = stateList[this.value];
                    $("#t1") // the text box
                        .autocomplete({ source: countyList })
                        .val('');
                });

                // trigger a 'fake' change, to set up the autocomplete
                $('#s1').trigger('change');
            }});
});

說明: stateList是列表的列表。 該列表的內部索引是狀態名稱,或者在我的情況下是狀態縮寫(AL,AK,AZ等)。 stateList中的每個項目都是字符串列表,每個項目都是該州的縣名。

代碼的作用是:

  • 為文檔准備事件注冊一個功能。
  • 在該功能中,通過ajax獲取縣列表的CSV。
  • 在該ajax調用的成功回調中,解析結果。 對於每個新狀態,將一個項目添加到stateList ,然后將該狀態添加到下拉列表中。 將縣添加到該州的縣列表中。 還將更改事件處理程序綁定到下拉列表。
  • 在更改處理程序中,將自動完成功能應用於“縣名”文本框。 來源是下拉列表中所選州的縣名列表。

編輯 -僅供參考,我從該列表中獲得了縣列表 ,而只是用逗號替換了制表符。 不必用逗號替換選項卡,但它使我可以更輕松地在文本編輯器中瀏覽列表。 如果不使用逗號替換制表符,則需要修改對elt.split()的調用以拆分制表符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM