2011-02-04 89 views
5

我想使用自動完成小部件來允許某人通過在文本框中輸入員工姓名來選擇員工,但我希望表單發佈ID員工,而不是員工的名字。我提供了數據,即員工姓名作爲來源。 .js中的標籤和值與我提供的源代碼相同,我如何才能將員工姓名和ID分開。如何在jQuery UI自動完成源事件中設置ID

$("#txtEmployeeName").autocomplete({ 
        var suggestions = [] ; 
        //define callback to format results 
        source: function(req, add){ 
        ajax call...     
        on success: function(data) 
        {     
         suggestions = data.split('|'); 
         add(suggestions); 
        } 
        select: function(e, ui) { 
        //create formatted friend 
        var friend = ui.item.value, 
         span = $("<span>").text(friend) 
         $("#"+ $(this).attr("id")).val(span); 
        } 

       }); 

回答

8

您需要將json對象傳遞給源屬性。

然後你的ui.item就是對象,用Id,值,你想要的一切。

$(function() {     
    var students = [{id: 1322,label: "student 1"},{id: 2,label: "Student 2"}]; 
    $("#search-student").autocomplete({ 
     source: students, 
     minLength: 2, 
     select: function(event, ui) { 
       window.location.href="/?studentId=" + ui.item.id; 
     }     
    });    
}); 

查看jQuery的getJSON:http://api.jquery.com/jQuery.getJSON/以通過ajax獲取json。

+0

謝謝,效果很好.... – deepu 2011-02-05 04:10:15