Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

                });   
like image 651
deepu Avatar asked Feb 04 '11 07:02

deepu


People also ask

How to set autocomplete value using jQuery?

To enable an autocomplete in jQuery UI, we will be using the enable() method. jQuery UI enable() method is used to enable the autocomplete.

How autocomplete works jQuery?

In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time. The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.

How can create autocomplete search box in jQuery?

Syntax: $("TagId"). autocomplete({ source : itemList // List of Words. })

What is UI autocomplete?

ui-autocomplete : The menu used to display matches to the user. ui-autocomplete-input : The input element that the autocomplete widget was instantiated with.


Video Answer


1 Answers

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.

like image 63
Cyril Gandon Avatar answered Sep 22 '22 05:09

Cyril Gandon