Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

how to set id in jquery ui autocomplete source event

I wanted to use the auto complete widget to allow someone to select an employee by typing in an employee name into the text box, but I want the form to post the ID of the employee, not the employee name.I provided the data ie the employee names as source. the label and value in the .js is same as the source i provided how can i possible to get employee name and id separate.

  $("#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);  
                    } 

                });   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to pass a json object to the source propertie.

Then your ui.item is the object, with Id, value, everything you want.

$(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;
        }                   
    });             
});

Look at jQuery's getJSON : http://api.jquery.com/jQuery.getJSON/ to get json via ajax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...