JQuery UI autocomplete change event - resetting selection ID

Viewed 27695

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?

2 Answers
Related