2013-01-07 74 views
0

我是新來的自動完成。我可以從API調用中獲取數據,並將其設置爲源,並使自動完成功能在基本級別上工作。但是,當我選擇一個值時,我還希望能夠:JQuery自動完成 - 從源中選擇多個值

  1. 在使文本輸入值成爲源值的同時在文本輸入中顯示標籤。
  2. 自動填寫一些其他輸入。

例如,我有3個輸入框,其中包含以下id:customer,customer_number,customer_representative。我有一個在下面的JSON格式返回數據的API:

{"request": 
    {"request_type":"whatever", 
    "response":[ 
    { 
     "customer_id":"123456", 
     "customer_name":"TEST CUSTOMER", 
     "customer_account":"ABC987", 
     "customer_rep_id":"567", 
     "customer_rep_id":"John Smith", 
    } 
    ] 

    } 
} 

這裏是我到目前爲止的代碼:

var url = [API URL W/ PARAMS]; 
$.getJSON(url, function(data) 
{  
    var src = []; 
    $.each(data.response, function(index, value) { 
     var customer= data.response[index]['customer_name']; 
     src.push(customer); 
    });  

    $("#customer").autocomplete({ 
     source: src 
    }); 
} 

這將有助於爲客戶輸入框自動完成,但價值是一樣的作爲客戶名稱。閱讀官方文檔(http://api.jqueryui.com/autocomplete/)後,似乎我應該能夠使用select(event,ui)來填充其他2個輸入框,但是我不知如何。

任何幫助,非常感謝。

回答

0

玩了一下之後,它終於點擊了我的大腦。 爲了實現這兩個目標,我只是將源代碼創建爲一個多維數組,其中包含我想要檢索的額外值,然後添加了一個回調函數來填充我想填寫的其他任何字段。

var src = []; 
    $.each(data.response, function(index, value) { 
    var customer= data.response[index]['customer_name']; 

    //Also retrieve other values that I want to use 
    var customer_id= data.response[index]['customer_id']; 
    var customer_rep_id= data.response[index]['customer_rep_id']; 
    var customer_rep_name= data.response[index]['customer_rep_name']; 

    //Make this a multi array 
    src.push({label: customer, value:customer_id, rep_id = customer_rep_id, rep = customer_rep_name }); 
}); 

//Added a callback function 
$("#customer").autocomplete({ 
    source: src, 
    select: AutoCompleteSelectHandler 
}); 


//This function auto-populates other inputs 
function AutoCompleteSelectHandler(event, ui) { 
    //Populate rep box 
    $("#customer_representative").val(ui.item.customer_rep_name); 
}