Using JQuery UI AutoComplete returns last item in dataset when item is selected

I am trying to create an autocomplete textbox. I have a textbox called countryName

which the user enters in some parts of the country name. The names of the matching countries are displayed, and when the user clicks on the country name, their ID should be placed in a hidden field under the name countryId

.

The problem is that when one of the matching country names is selected, the ID of the most recent matches is placed in the field countryId

, not the ID of the selected item.

For example:

Enter Ja in the text box countryName

to find all countries starting with Ja. Results returned: Jamaica (countryId = 108) and Japan (countryId = 110). If I select / click on, say Jamaica - the value that is filled in the field countryId

(hidden field) is 110, not 108.

Here is the code I was working with. I've used it on other projects, but can't seem to find that at this different time to get it to misbehave.

var c_id = 0;   // countryId
var sp_id = 0;  // stateprovinceId

$('#CountryName').autocomplete({
    source: function (request, response) 
        $.ajax({
            url: '/Ajax/CountrySearch',
            type: 'POST',
            dataType: 'json',
            data: { param: request.term },
            success: function (data) {
                response($.map(data, function (item) {
                    c_id = item.id;
                    return {
                        label: item.name,
                        value: item.name
                    }
                }));
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(xhr.responseText);
                alert(thrownError);
            }
        });
    },
    select: function () {
        event.preventDefault();
        alert(countryId);
        $('#CountryID').val(c_id);
    }
});

      

A second pair of eyes would be appreciated.

+3


source to share


1 answer


  • $.map

    in your callback success

    iterates over the response and assigns a global variablec_id

  • when done is c_id

    equal to the id

    last displayed item
  • you then assign that value in the select event with $('#CountryID').val(c_id);

Change source to return item.id

as values:

response($.map(data, function (item) {
    return {
        label: item.name,
        value: item.id
    }
}));

      



and change the way you handle the event to take advantage of the arguments in the callback and get the value

select: function (e, ui) {
    e.preventDefault();
    $(this).val(ui.item.label);
    $('#CountryID').val(ui.item.value);
}

      

And demo http://jsfiddle.net/4doz4yuj/

+2


source







All Articles