views:

53

answers:

1

I'm using the AutoComplete UI widget for a form to allow users to type in a customer name. The idea is that they can either select an existing customer and populate other fields in the form, or they can free-type a new customer to be created. When a user selects an existing customer, I use the select event to populate a hidden input to store the ID associated with that customer.

The problem I'm having is if a user first selects a customer from the list but then goes in and edits the text, in effect creating a new customer, I need to be able to clear out that hidden input ID value.

I referred to this SO question and created the following code:

$(function() {
            $("#customerName").autocomplete({
                source: "/Customers/CustomerListJSON",
                minLength: 2,
                select: function(event, ui) {
                    $("#customerId").val(ui.item ? ui.item.Id : "");
                },
                change: function(event, ui) {
                    try {
                        $("#trace").append(document.createTextNode(event.originalEvent.type + ", "));
                        if (event.originalEvent.type != "menuselected")
                            $("#customerId").val("");
                    } catch (err) {
                        $("#customerId").val("");
                    }
                }
            });
        });

The problem is that the change event is fired on blur, so if a user selects a customer, the hidden input value is populated, but as soon as they move focus off the input box it's cleared right away. However, if I exclude the blur event from the event.originalEvent.type test, then the hidden field's value never gets reset in the original scenario where a user edits a previously-selected value.

Has anyone had to tackle this before, and if so can you offer some guidance on how I can manage that hidden input's value so it's populated only when an item is selected from the list and cleared with any other value?

A: 

Looks like I solved this pretty quickly on my own. Referring to the JQuery UI wiki, the ui item in the change event is the same one in the select event, so I can modify my code to read like this:

$(function() {
    $("#customerName").autocomplete({
        source: "/Customers/CustomerListJSON",
        minLength: 2,
        select: function(event, ui) {
            $("#customerOrganizationId").val(ui.item ? ui.item.Id : "");
        },
        change: function(event, ui) {
            $("#customerOrganizationId").val(ui.item ? ui.item.Id : "");
        }
    });
});

There's no need to test for the event, just for whether there is an item in the ui argument. The ID setting in the select event is probably redundant, but to be safe I'm going to keep both.

Josh