views:

83

answers:

1

Hello, I have a jquery ui autocomplete widget in a form and I'd like to preselect its value from a database. My autocomplete works in the following way: the id is a number, tha label and the value are the same and are a concatenation of id + " - " + description. When a value from the autocomplete is selected, a hidden field's value is set to the value of id. Then, the hidden field value is saved to the db when the form is submitted. When the user comes back on the page for editing, I need to reload the value from the db: I set the idden field value again and then I would like to precompile the value of the autocomplete widget with the concatenation of id + " - " + description taken form the db. I think I should trigger the event of selecting a row in the autocomplete, but I don't know how to do. Do you have any ideas? Thank you Here is the code of the autocomplete:

$('#codice_contratto').autocomplete({
    source: 'do_contratto.php',
    select: function(event, ui) {
                $('#id_contratto').val(ui.item.id);
            }
});
A: 

In the server-side code that returns the page for editing, I would recommend just setting the value of both the textbox with autocomplete as well as the hidden field to their correct values as its returned from the server. That would be a server-side solution, and your HTML would look something like this:

<input type="textbox" id="condice_contratto" value="1 - the description" />
<input type="hidden" id="id_contratto" value="1" />

The JQuery autocomplete plug-in works gracefully when the element's value is preset. There isn't really a notion of 'selecting' an item in it per-se. It just rides on top of a textbox and sets its value with lots of fancy UI.

If you require a client-side solution, just do something like this:

$(document).ready(function() {
   $('#condice_contratto').val(current_id + ' - ' + current_description);
   $('#id_contratto').val(current_id);
}

This assumes the variables current_id and current_description are set to their correct values.

KevinM