views:

706

answers:

2

Hi,

I call the autocomplete jquery with the result of a GET request. The autocomplete function call looks like this:

$('#id_project_owner_externally').autocomplete('/pm/contact_autocomplete');

The url /pm/contact_autocomplete returns a list of tuples. The first part of the tuple is the name of the contact and the second part of the tuple is the id of the contact.

The corresponding function (part of a django view) looks like this:

def iter_results(results):
        if results:
            for r in results:
                yield '%s|%s\n' % (r.first_name, r.id)

Now I'm wondering what jquery autocomplete is doing with the first_name + id tuple. Acutally the first_name is put into the input field. But what happens with the id part. This is the important information that I need.

Can I tell jquery that the id should be placed into a certain hidden field?

link to js source

Edit: The solution

<script type="text/javascript"><!--//
        $('#id_project_manager_externally').autocomplete('/pm/contact_autocomplete').result(function(event, item) {$('#id_project_manager_externally_hidden').attr("value", item[1]);});//--></script> 
+2  A: 

You need to look into the jquery.autocomplete.js source code, what your python code does is simply return the id and name separated by a hash char, one record per line. The autocomplete javascript handles that output, thus that is the part of the code you need to modify to put the ids into your hidden fields.

code_burgar
Hack into the autocomplete js is not really my preferred way. hmm.. seems to be more complicated than expected.
Tom Tom
+2  A: 

The plugin docs have this example:

var data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ];
$("...").autocomplete(data, {
  formatItem: function(item) {
    return item.text;
  }
}).result(function(event, item) {
  location.href = item.url;
});

So you basically can have a .result() option that you use to populate a hidden field. e.g. $('#my_hidden_field').val(item.extra_value);

Joel L
This looks promising. I will give it a try.
Tom Tom
This is the correct answer. With the .result() option you can replace the value of a hidden field. The result part is triggered after a user selected an option out of the autocomplete dropdown.
Tom Tom