Shokwave
Shokwave

Reputation: 329

Jquery autocomplete fire on enter keypress

Im using Jquery UI Autocomplete and it works great but I am trying to get around this issue and would appreciate some help with. The autocomplete is on a textbox inside asp panel, the default behaviour on the form on Enter key is to submit the form. If the user types something into the Autocomplete textbox and presses Enter, I want the auto complete web service to fire off and brings back the results on Enter. I read online I was suppose to handle the Keypress event for autocomplete, I have been trying but not sure on how to call the autocomplete to fire on the keypress, I am showing my code below, if someone has an idea how this can be done please show by an example in the code since im having a problem with the correct syntax to call the function on the keypress, your helps appreciated, here is the code.

//Attach autocomplete to txtCity so user can lookup SPLCS by cities

        var city;
        var txtCity = $("[id$=txtAutoCity]")
        $(txtCity).autocomplete({
            source: function (request, response) {
                request.term = request.term.replace(/[^a-zA-Z\s]+/, "")
                $.ajax({
                    url: "../../Services.asmx/GetOfficesByCity",
                    data: "{ 'city': '" + request.term + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data.d, function (item) {

                            if (data.d != undefined) {
                                return {
                                    value: item.Display,
                                    result: item.CommaDelimited
                                }

                            }
                            else {
                                return true;
                            }
                        }))
                    },

                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            },
            autoFill: false,
            minLength: 2,
            delay: 800,
            mustMatch: false,
            selecFirst: false,
            select: function (event, ui) {
                var selectedObj = ui.item;
                if (ui.item) {
                    city = ui.item.result.split(',')[0];

                    $("[id$=txtCity]").val(ui.item.result.split(',')[0]);
                    $("[id$=txtOffice]").val(ui.item.result.split(',')[1]);
                    $("[id$=txtDistrict]").val(ui.item.result.split(',')[2]);


                }
            },
            // Any action to be performed once the auto complete list closes
            close: function (event) {

            }
        }).keypress(function (e) {
            if (e.keyCode === 13) {
                //How to cancel default submit behaviour of form and call this
                //autocomplete function to fire??   
                e.preventDefault();
                //my_search_function($(txtCity).val())
            } 
        });

Upvotes: 3

Views: 6805

Answers (3)

user3700666
user3700666

Reputation: 31

To solve this problem you can add a search property in your autocomplete and a new variable, following these steps:

  • Create a new variable (var canPass = false);
  • Add the search property inside of your autocomplete;
  • Fire the search function in the keypress event;

So, the result is:

//Attach autocomplete to txtCity so user can lookup SPLCS by cities

    var canPass = false;
    var city;
    var txtCity = $("[id$=txtAutoCity]")
    $(txtCity).autocomplete({
        source: function (request, response) {
            request.term = request.term.replace(/[^a-zA-Z\s]+/, "")
            $.ajax({
                url: "../../Services.asmx/GetOfficesByCity",
                data: "{ 'city': '" + request.term + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataFilter: function (data) { return data; },
                success: function (data) {
                    response($.map(data.d, function (item) {

                        if (data.d != undefined) {
                            return {
                                value: item.Display,
                                result: item.CommaDelimited
                            }

                        }
                        else {
                            return true;
                        }
                    }))
                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        },
        autoFill: false,
        minLength: 2,
        delay: 800,
        mustMatch: false,
        selecFirst: false,
        select: function (event, ui) {
            var selectedObj = ui.item;
            if (ui.item) {
                city = ui.item.result.split(',')[0];

                $("[id$=txtCity]").val(ui.item.result.split(',')[0]);
                $("[id$=txtOffice]").val(ui.item.result.split(',')[1]);
                $("[id$=txtDistrict]").val(ui.item.result.split(',')[2]);


            }
        },
        // Any action to be performed once the auto complete list closes
        close: function (event) {

        },
        search: function (value, event) {
            if (!canPass) {
               event.preventDefault();
            }
            else {
               canPass = false;
            }
        },
    }).keypress(function (e) {
        if (e.keyCode === 13) {
           canPass = true;
           $(txtCity).autocomplete("search", ($txtCity).val());
        }
    });

So, with this code your autocomplete starts to search when you press ENTER.

Upvotes: 3

toepoke.co.uk
toepoke.co.uk

Reputation: 827

Please see accepted answer, disregard the following

Firstly I would suggest IMHO you're thinking about this the wrong way around. The notion of the autocomplete is for the user to continue typing until the answer is fully resolved (or select from the given options for the one they want, which incidentally can be achieved with the arrow keys to select, with ENTER selecting the result).

That said if you really want to override the ENTER behaviour I would suggest doing this separately through "keydown" rather than as part of the autocomplete widget. The following jsFiddle should you an idea of what to look at: http://jsfiddle.net/2Z25f/

Kind regards,

toepoke.co.uk

Upvotes: 0

leon.io
leon.io

Reputation: 2824

You need to fire the search function on the autocomplete object.

($txtCity).autocomplete( "search", "TheSearchValueToSend" )

More info at the Jquery Doco Site

Upvotes: 1

Related Questions