如何在jquery ui自动完成源事件中设置id

dee*_*epu 5 jquery jquery-ui autocomplete

我想使用自动完成小部件允许某人通过在文本框中键入员工姓名来选择员工,但我希望表单发布员工的ID,而不是员工姓名.我提供了数据,即员工姓名作为来源..js中的标签和值与我提供的源相同,我怎样才能将员工姓名和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);  
                    } 

                });   
Run Code Online (Sandbox Code Playgroud)

Cyr*_*don 8

您需要将json对象传递给source属性.

然后你的ui.item是对象,Id,value,你想要的一切.

$(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;
        }                   
    });             
});
Run Code Online (Sandbox Code Playgroud)

看看jQuery的getJSON:http://api.jquery.com/jQuery.getJSON/通过ajax获取json.